11 Jul 2016
5 分钟阅读
深入剖析 HashSet 和 HashMap 实现深入剖析 HashSet 和 HashMap 实现
HashSet是一个包含非重复元素的集合,如何实现的,要从底层实现代码看起。
背景
首先非重复元素如何定义,看Set的描述:
More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.
Set不会找到两个元素,并且两个元素满足e1.equals(e2)为true;并且最多只有一个null元素。
如果没有重写equals方法,查看Object类中equal方法的实现,==比较的其实是两个对象在内存中的地址。
public boolean equals(Object obj) {
return (this == obj);
}
说起equals方法,就不得不说hashCode方法了。Java中对于hashCode有个常规协定
The general contract of hashCode is: