所有的方法,add、remove都是通过调用hashmap的方法实现的。
就连size也是。
那么是哪一段代码实现了去除重复的呢。
请知道的帮忙,先谢谢了。
[quote]set接口在保证不重复做了什么工作,这点是我最疑惑的
[/quote]
1.接口 是对行为的抽象与规范。
2.去重复,只是底层一个算法或者策略问题,与接口没有关系。
下面是HashSet中的add方法
[code="java"]
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
//PRESENT is a dumy object .
[/code]
插入到插入到HashMap中的是key,将e作为key了,当然就去掉了重复元素.
因为HashMap中的key是唯一的。
可以看src.zip里面关于HashSet&TreeSet的add(E e)方法的定义呀.
[code="java"]
private transient NavigableMap m;
private static final Object PRESENT = new Object();
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
[/code]
看到这里就很明显了.
当调用HashSet&TreeSet的add方法时,add方法里面的元素其实是保存在一个Map对象的键里面的,这样就可以做到避免重复.
[code="java"]
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with key, or
* null if there was no mapping for key.
* (A null return can also indicate that the map
* previously associated null with key.)
*/
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
[/code]
这个是hashmap的put方法的定义,如果key值存在于map中,那么就用new value覆盖掉old value,这样就实现了避免重复.
这下楼主所有的疑问都解决了,求给分