1 Object方法中有这样两个方法 hashcode equals 用来比较对象
原则 1, == 只判断两个对象引用值是否相等
Student stu1 = new Student();
Student stu2 = new Student();
Student stu3 = stu1
则 stu1 == stu2 false
stu1 == stu2 true
2, equals 先判断hashCode(默认为内存地址)是否相等 后判断 equals 是否相等
如果hashCode 不相等 则在用equals 比较时 一定不会相等 因为 equals 比较结果是建立在 hashCode 结果之上的 可以理解为并的效果(只是这么理解)
引申结果:hashCode 不等 则equals一定不等 只有 hashCode 相等 也不一定相等 只有两者同时满足时 才相等
所以一般自定义类时 当我们重写equals方法是 都习惯的去重写hashCode方法 但不是必须
默认这些方法都是继承于Object
package com.gui.test;
class Student{
int num;
String name;
Student(int num,String name){
this.num=num;
this.name=name; }
public int hashCode(){ //重写hashCode的方法
return num*name.hashCode(); }
public boolean equals(Object o) {
Student s=(Student)o;
return true; //&&的优先级比==低,所以前面不必加括号
}
public String toString(){return num+":"+name; }
}
package com.gui.test;
import java.util.HashSet;
public class HashSetTest {
public static void main(String[] args) {
HashSet<Student> hs = new HashSet<Student>();
hs.add(new Student(1, "zhangsan"));
hs.add(new Student(2, "lisi"));
hs.add(new Student(3, "wangwu"));
hs.add(new Student(1, "zhangsan"));
for (Student stu : hs) {
System.out.println(stu.toString());
}
Student stu1 = new Student(2,"gui");
Student stu2 = new Student(2,"gui");
Student stu3 = stu1;
if(stu1 == stu2) System.out.println(" stu1 == stu2 ");// false
if(stu1 == stu3) System.out.println(" stu1 == stu3 ");//true
if(stu1.equals(stu2)) System.out.println(" stu1.equals(stu2) "); //true
}
}