• 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来比较

  • 相关阅读:
    android存储訪问框架Storage Access Framework
    hdu 5338 ZZX and Permutations (贪心+线段树+二分)
    集成CCFlow工作流与GPM的办公系统驰骋CCOA介绍(三)
    PHP中文分词扩展 SCWS
    使用docker 搭建基础的 mysql 应用
    UVA 11090 Going in Cycle!!(Bellman-Ford推断负圈)
    HDU 5237 Base64
    Android 自己定义主菜单
    HDU 1018 Big Number 数学题解
    python经常使用的十进制、16进制、字符串、字节串之间的转换(长期更新帖)
  • 原文地址:https://www.cnblogs.com/mike-mei/p/11146531.html
Copyright © 2020-2023  润新知