话(鄙)不(人)多(很)说(懒),把进口的代码拉上来!
哈哈哈,开玩笑。
首先来说一下List集合和Set集合的区别。
List集合特点:存储和取出的元素数据一致(有序),元素可以重复,每个元素都存在一个对应的整数索引。
Set集合特点:一个不包含重复元素的collection,不保证迭代顺序(无序)。
创建一个Map对象,初始化HashSet
public class HashSets {
private transient HashMap map;
private static final Object PRESENT = new Object();
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
return map.put(e, PRESENT) == null;
}
}
结论:HashSet底层依赖于HashMap,所以接着来分析HashMap。
public class HashMap {
/**
* example:我们进行一个添加,HashSet hs = new HashSet();
* hs.add("快乐柠檬虾");
* add()方法中又调用了put(),这里key就是"快乐柠檬虾",即key = "快乐柠檬虾";
*/
public V put (K key, V value) {
//判断哈希表是否存在,如果不存在,创建一个哈希表
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null) return putForNullKey(value);
//hashCode()可能导致结果改变
int hash = hash(key);
//通过hashCode()计算出来的哈希码值在表中进行查找,是否存在。
int i = indexFor(hash, table.length);
for (Entry e = table[i]; e != null; e = e.next) {
Object k;
//e.hash:哈希表中对应索引的哈希值 hash:新添加进的元素计算的哈希值
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;
}
transient int hashSeed = 0;
/**
* 决定这个方法的返回值是hashCode()
*/
final int hash(Object k) {
int h = hashSeed;
if (0 != h && instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
//调用对象的hashCode()获取对象的哈希码值
h ^= k.hashCode();
//位运算
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
}
注释写的很明确了哦,通过hashCode()来计算一个哈希值,当哈希值相同的时候,在调用equals()判断,equals()返回true。进入if(){},里面操作的都是value,然后return。不会进行addEntry();
,
所以最终得到的结论:
HashSet集合底层的数据结构是哈希表,哈希表存储元素的时候保证元素的唯一性依赖于两个方法,一个是hashCode(),一个是equals() 。
当两个对象在调用hashCode方法获取哈希码值是相同的时候,也不能说明是同一个对象,还需要调用equals()进行判断,如果equals()返回的是true,那么说明两个对象是同一个对象,既然是同一个对象,就不能进行存储,这样就保证了元素的唯一性。
当两个对象在调用hashCode方法获取哈希码值是相同的时候,也不能说明是同一个对象,还需要调用equals()进行判断,如果equals()返回的是true,那么说明两个对象是同一个对象,既然是同一个对象,就不能进行存储,这样就保证了元素的唯一性。