- Java code
public class Student { private String name; private int age; public boolean equals(Object o) { boolean flag = false; if (o != null) { if (this == o) { flag = true; } else { if (o instanceof Student) { Student s = (Student) o; if (this.name.equals(s.name) && this.age == s.age) { flag = true; } } } } return flag; } public static void main(String[] args) { Student s1 = new Student(); s1.name = "kaka"; s1.age = 10; Student s2 = new Student(); s2.name = "kaka"; s2.age = 10; System.out.println(s1.equals(s2)); }}
------解决方案--------------------
逻辑合并了一下
- Java code
public class Student{ private String name; private int age; public boolean equals(Object o) { boolean flag = false; if(o != null) { if(this == o) { flag = true; } else if(o instanceof Student) { Student s = (Student)o; if(this.name.equals(s.name) && this.age == s.age) { flag = true; } } } return flag; } public static void main(String[] args) { Student s1 = new Student(); s1.name = "kaka"; s1.age = 10; Student s2 = new Student(); s2.name = "kaka"; s2.age = 10; System.out.println(s1.equals(s2)); }}
------解决方案--------------------
- Java code
public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Student)) return false; Student s = (Student) obj; return this.name.equals(s.name) && this.age == s.age; }
------解决方案--------------------
用o.getClass()==Student.class 会不会更精确一点
------解决方案--------------------
还可以更好一点
- Java code
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; //注意,这里如果用 (obj instanceof Student) 来判断的话,那么Student所有的子类 //的 equals 方法就不能有改变 Student s = (Student) obj; return name.equals(s.name) && age == s.age; }
------解决方案--------------------
- Java code
public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (obj.getClass() != this.getClass()) return false; Student other = (Student) obj; return (other.name == null ? this.name == null : other.name.equals(this.name)) && (other.age == this.age); }