public boolean equals(Object obj) { return (this == obj); }
public class Demo { public static void main(String[] args) { Student stu1 = new Student("awu",22); Student stu2 = new Student("awu",22); System.out.println(stu1.equals(stu2)); /*因为Student这个JavaBean没有重写关于属性值相等的equals()方法 ,所以默认比较的是地址值,从而输出结果为false*/ } }
public class Student { private String name; private Integer age; public Student(){ } public Student(String name,Integer age){ this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public int hashCode(){ final int prime = 31; int result = 17; result = prime * result name.hashCode(); result = prime * result age; return result; } @Override public boolean equals(Object obj){ if(this == obj) return true; if(obj == null) return false; if(getClass() != obj.getClass()) return false; final Student other = (Student)obj; if(name.equals(other.name)){ return false; } if(age.equals(other.age)){ return false; } return true; } }
public class Demo { public static void main(String[] args) { Student stu1 = new Student("awu",22); Student stu3 = new Student("awu",33); Student stu2 = new Student("awu",22); Set set = new HashSet(); set.add(stu1); set.add(stu2); set.add(stu3); System.out.println(set.size()); /*输出结果为2*/ } }
public class Demo { public static void main(String[] args) { Student stu1 = new Student("awu",22); Student stu3 = new Student("awu",33); Student stu2 = new Student("awu",22); ArrayList list = new ArrayList(); list.add(stu1); list.add(stu2); list.add(stu3); System.out.println(list .size()); /*输出结果为3*/ } }
public class Student { private String name; private Integer age; public Student(){ } public Student(String name,Integer age){ this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public int hashCode(){ final int prime = 31; int result = 17; result = prime * result name.hashCode(); result = prime * result age; return result; } @Override public boolean equals(Object obj){ if(this == obj) return true; if(obj == null) return false; if(getClass() != obj.getClass()) return false; final Student other = (Student)obj; if(name.equals(other.name)){ return false; } if(age.equals(other.age)){ return false; } return true; } }