zoukankan      html  css  js  c++  java
  • java构造方法和重写equals

    Cell的构造函数
    package Test;
    
    import java.util.Objects;
    
    public class Cell {
        int a;
        int b;
    
        public int getA() {
            return a;
        }
    
        public void setA(int a) {
            this.a = a;
        }
    
        public int getB() {
            return b;
        }
    
        public void setB(int b) {
            this.b = b;
        }
    
        Cell (int a, int b) {
             this.a=a;
             this.b=b;
        }
    
        @Override
        public String toString() {
            return this.a+","+this.b;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Cell cell = (Cell) o;
            return a == cell.a &&
                    b == cell.b;
        }
    
        @Override
        public int hashCode() {
    
            return Objects.hash(a, b);
        }
    }

    调用

    package Test;
    
    
    import java.util.ArrayList;
    import java.util.Collection;
    
    public class testHelloWorld {
    
        public static void main(String[] args) {
            Collection<Cell> cells = new ArrayList<Cell>();
            cells.add(new Cell(1, 2));
            cells.add(new Cell(1, 3));
            cells.add(new Cell(2, 2));
            cells.add(new Cell(2, 3));
            Cell cell = new Cell(1, 3);
            System.out.println(cell);
            System.out.println(cells);
    // List集合contains方法和对象的equals方法相关
            boolean flag = cells.contains(cell);
    // 如果Cell不重写equals方法将为false
            System.out.println(flag); // true
        }
    }

    equals与 == 的区别

    "=="是值比较,对于引用类型变量而言,该变量保存的是对象的地址,所以使用"=="比较时,意思为两个变量的地址是否相等,换句话说就是看两个变量引用的是否为同一个对象

    equals是内容比较,对于两个引用变量而言,是比较两个变量所引用的对象内容是否相同。

    举个例子, 就好像一对双胞胎,他们是两个独立的个体,是两个对象。所以那么用"=="比较是 false。但是因为他们“长得一样”,所以equals方法比较是true。

    我们也可以变相的理解为:"=="是判断是否为同一个,而"equals"是判断像不像。

    java为什么要重写equals ?!

    默认equals在比较两个对象时,是看他们是否指向同一个地址的。
    但有时,我们希望两个对象只要是某些属性相同就认为他们的quals为true。比如:
    Student s1 = new Student(1,"name1");
    Student s2 = new Student(1,"name1");
    如果不重写equals的话,他们是不相同的,所以我们要重些equals,判断只要他们的id和名字相同equals就为true,在一些集合里有时也这样用,集合里的contain也是用equals来比较

  • 相关阅读:
    faster with MyISAM tables than with InnoDB or NDB tables
    w-BIG TABLE 1-toSMALLtable @-toMEMORY
    Indexing and Hashing
    MEMORY Storage Engine MEMORY Tables TEMPORARY TABLE max_heap_table_size
    controlling the variance of request response times and not just worrying about maximizing queries per second
    Variance
    Population Mean
    12.162s 1805.867s
    situations where MyISAM will be faster than InnoDB
    1920.154s 0.309s 30817
  • 原文地址:https://www.cnblogs.com/mike-mei/p/11146531.html
Copyright © 2011-2022 走看看