java类,重新equals方法。
A obj1 = new A();
init....
A obj1 = new A();
init....
sysout(obj1.equals(obj2)); //=true
Set<A> objs = new HashSet<A>();
objs.add(obj1);
sysout(objs.add(obj2)); //=true
根据HashSet的api说明,只要 equals = true,add就应该返回false。代码却返回true。
实际上,重写equals有个原则,最好同时重写hashCode方法,并且满足:
obj1.equals(obj2) (= true) 则obj1.hashCode() == obj2.hashCode() (=true)
但obj1.equals(obj2) (=false),不要求 obj1.hashCode() = obj2.hashCode() (=false)。
特别是在遇到hash的时候,重写equals,必须重写hashCode。