HashSet类
此类实现 Set 接口,由哈希表(实际上是一个 HashMap 实例)支持。它不保证 set 的迭代顺序;特别是它不保证该顺序恒久不变。此类允许使用null元素。HashSet保证元素唯一。
底层数据结构是哈希表,哈希表依赖于哈希值存储
添加元素时保证元素唯一,本质底层依赖两个方法:
int hashCode()
boolean equals(Object obj)
1.HashSet是如何保证元素唯一的? 先比较hashCode方法 再比较equals方法//HashSet实际由HashMap调用add 调用add put的 put 返回的是 putVal(里面调用的是hash值 hash在进行比较如果哈希值不等 直接返回 要是哈希值相等 就进行equals比较要是equals不相等返回,要是相等就剔除)
2.HashSet是如何导致元素无序? 元素存储到哈希表结构当中是通过 对象的hashCode经过某种运算产生的相对不确定的数
导致元素无序 是hash方法进行返回的
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
3.HashSet为什么和存储不一样,却每次遍历的顺序都一样? 因为每次遍历的时候是同一个对象,同一个对象产生的哈希值是一样的
public class SetDemo {
public static void main(String[] args) {
HashSet<Studen> hs = new HashSet<>();
hs.add(new Studen("张三", 18));
hs.add(new Studen("张三", 28));
hs.add(new Studen("张三", 18));
for (Studen studen : hs) {
System.out.println(studen.getName() + "|" + studen.getAge());
}
}
}
class Studen {
private String name;
private Integer age;
public Studen() {
super();
}
public Studen(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Studen [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Studen other = (Studen) obj;
if (age == null) {
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
HashSet底层add原码解析
public class HashSetDemo01 {
public static void main(String[] args) {
HashSet<String> hs = new HashSet<>();
hs.add("ab");
hs.add("ac");
hs.add("ba");
hs.add("bc");
for (String s : hs) {
System.out.println(s);
}
System.out.println("============");
Iterator<String> it = hs.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
}
}
class HashSet {
private transient HashMap<E,Object> map;
private static final Object PRESENT = new Object(); 0x0001
public HashSet() {
map = new HashMap<>();
}
"ab"
public boolean add(E e) {
"ab"
return map.put(e, 0x0001)==null;
}
}
class HashMap {
static final float DEFAULT_LOAD_FACTOR = 0.75f;
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public V put(K key, V value) {
// hash("ab") "ab"
return putVal(hash(key), key, value, false, true);
}
1.哈希值的结果和存储的对象本身有关
2.哈希值的结果和存储的对象的hashCode有关
3.哈希值同时是通过异或和移位产生的一个整数值,这个值是没有规律,但是每次运算的结果是一样
4.哈希算法返回的哈希值是一个整数,这个整数作为索引存储在哈希表结构当中
5.判断两个元素是否重复比较 hashCode 还有 equals 方法
"ab"
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
32457 "ab" 0x0001
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
}
class String {
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
}