HashSet的contains方法de解释是不是有问题

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值