62,614
社区成员
发帖
与我相关
我的任务
分享
import java.util.*;
public class TestHashSet{
public static void main(String[] args){
HashSet hs = new HashSet();
for(int i=1;i<=20;i++){
hs.add(i);
}
System.out.println(hs);
}
}
public boolean add(E e) { //hashSet 的add方法,调用了 hashMap的put方法
return map.put(e, PRESENT)==null;
}
public V put(K key, V value) {//hashMap的put方法
if (key == null)//判断key是否为空
return putForNullKey(value);
int hash = hash(key.hashCode());//得到key的hash值
int i = indexFor(hash, table.length);//得到key在Hash表中的位置索引
for (Entry<K,V> e = table[i]; e != null; e = e.next) { //for循环主要是查找表中是否有与要插入
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;
}
}
//下面的代码主要是处理 由于在hash表中没找到与要插入的对象相同的对象
modCount++;
addEntry(hash, key, value, i); //在Hash表中增加一个元素
return null;
}
void addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
if (size++ >= threshold) //扩容了
resize(2 * table.length); //为原容量得2
倍
}