首先这3个都是Object超级类种的属性或者方法。
equal如果不重写的话,实质上也是调用==方法,也就是比较的2个对象是不是同一个。
如果需要比较2个对象的是否相等,比较的是内容的话,就需要重写equals方法。
例如一个Person类:
classs Person{
private String id;
private String name;
public Person(String id,String name){
this.id = id;
this name =name;
}
}
Person p1 = new Person("1","xiaobai");
Person p2 = new Person("1","xiaobai");
不重写equals的情况下:p1.equals(p2) 返回false。
重写equals ,在equals中判断id和name 是否想等在返回,name就会返回true。
public Boolean equals(Object obj){
if(obj == null) return false;
if(this == obj) return true;
if(this.getClass != obj.getClass) return false;
return this.id == obj.id && this.name = obj.name;
}
hashCode和equals重写,需要在散列的数据结构中存储需要同时重写,否则没有一分钱关系。散列的数据结构,如:HashSet,HashTable,HaseMap.