HashSetのcontainsの方法deは問題があるかどうかを解釈します

2562 ワード

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;
}