first of all, exhibits the code:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
public class Test {
int value;
Test(int value) {
this.value = value;
}
public boolean equals(Object obj) {
if (obj instanceof Test) {
Test foo = (Test) obj;
return value == foo.value;
} else {
return false;
}
}
public static void main(String[] args) {
ArrayList list = new ArrayList();
HashSet set = new HashSet();
list.add(new Test(1));
set.add(new Test(1));
Iterator i = set.iterator();
while (i.hasNext()) {
Test temp = (Test) i.next();
System.out.println(temp.equals(new Test(1)));
}
System.out.println(list.contains(new Test(1)) + ","
+ set.contains(new Test(1)));
System.out.println(new Test(1).equals(new Test(1)) + ","
+ set.contains(new Test(1)));
}
}
about contains, why list is true while set is false?
my answer:
HashSet与ArrayList的contains算法多加入了hashCode的考量
看源码,HashSet的contains方法最终是通过HashMap中的:
/**
* Returns the entry associated with the specified key in the
* HashMap. Returns null if the HashMap contains no mapping
* for the key.
*/
final Entry <K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key.hashCode());
for (Entry <K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
可见,hash和equals方法都是介入因素
但这里奇怪ArrayList和HashSet的contains方法javadoc一模一样,分别是:
Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
开始真是迷惑了一下,若我没考虑错的话,HashSet的解释是否是漏写了hash的相关
若要相同,是否在Test类中再重写hashCode如:
public int hashCode() {
return value;
}