春招修仙系列 ——重写equals方法

概述:

RT,之前面试被问到如何重写equals方法,其实这个问题被问到的概率还是挺高的,固整理一下:

问题:

假设你有一个学生对象,有两个字段,字符串的姓名,整数的年龄,请重写equals。

思路:

重写equals的时候,要注意一些特殊值,比如是否是null,是否是自己本身等,重写equals的时候一定要重写hashCode,因为在一些容器中,判断相等的时候,hashcode是equals的先决条件。

代码:

public class Student {
  public int age;
  public String name;

  @Override
  public boolean equals(Object obj) {
    if (obj != null && obj instanceof Student) {
      return obj == this ? true : (this.age == ((Student) obj).age) && (this.name.equals(((Student) obj).name));
    }
    return false;
  }
}

测试结果:

public class Test {
  public static void main(String[] args) {
       	Student a = new Student();
		a.name = "张三";
		a.age = 13;
		Student b = new Student();
		b.name = "张三";
		b.age = 13;
		Student c = new Student();
		c.name = "李四";
		c.age = 13;
    }
}
System.out.println(a.equals(a));	//true
System.out.println(a.equals(b));    //true
System.out.println(a.equals(c));	//false
System.out.println(a.equals(null)); //false

猜你喜欢

转载自blog.csdn.net/Kirito19970409/article/details/86589499
今日推荐