先看看HashSet的类名
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
继承了AbstarctSet这个抽象类,这个抽象类里面实际有一个空的默认构造方法,重写的hashcode()和equals(),还有一个removeAll()方法是用来去交集的
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> {
//默认空的构造函数
protected AbstractSet() {
}
//重写equals方法
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Set))
return false;
Collection<?> c = (Collection<?>) o;
if (c.size() != size())
return false;
try {
return containsAll(c);
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
}
//重写hashcode方法
public int hashCode() {
int h = 0;
Iterator<E> i = iterator();
while (i.hasNext()) {
E obj = i.next();
if (obj != null)
h += obj.hashCode();
}
return h;
}
//去掉原集合与集合c的交集
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
if (size() > c.size()) {//本集合大小大于集合c大小,以本集合为基础来删
for (Iterator<?> i = c.iterator(); i.hasNext(); )
modified |= remove(i.next());//只要有一个删除成功,modified就是true
} else {//集合c大小大于本集合大小,以集合c为基础来删
for (Iterator<?> i = iterator(); i.hasNext(); ) {
if (c.contains(i.next())) {
i.remove();
modified = true;
}
}
}
return modified;
}
}
HashSet还实现了Set接口,Clonable接口(其中的clone方法在后面有提到) ,和序列化接口Serializble
package java.util;
import java.io.InvalidObjectException;
import sun.misc.SharedSecrets;
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
static final long serialVersionUID = -5024744406713321676L;//提供序列化标识
private transient HashMap<E,Object> map;//可见HashSet内部实际上是由HashMap实现的,基本上都是调用HashMap的方法来实现自己的方法
//HashSet将添加进来的元素设为内部HashMap的key值,把这个object对象设置为value值
private static final Object PRESENT = new Object();//
//初始化hashset,实际上就是初始化内部的hashmap
public HashSet() {
map = new HashMap<>();
}
//hashmap的又一种初始化方式,设置默认加载因子及默认容量,并把集合c添加到hashmap中
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
//初始化设置加载因子和容量
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
//在没填入加载因子的情况下进行初始化,初始化的加载因子为默认值
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
//初始化设置linkedhashmap
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
//获取迭代器,即获取map的所有值的迭代器,可见set的值是保存在map的key上的
public Iterator<E> iterator() {
return map.keySet().iterator();
}
//获取set的大小
public int size() {
return map.size();
}
//判断set是否为空
public boolean isEmpty() {
return map.isEmpty();
}
//set中是否包含对象o
public boolean contains(Object o) {
return map.containsKey(o);
}
//向set中添加元素
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
//删除set中的元素o
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
//清空set
public void clear() {
map.clear();
}
//实现clonable接口
@SuppressWarnings("unchecked")
public Object clone() {
try {
HashSet<E> newSet = (HashSet<E>) super.clone();
newSet.map = (HashMap<E, Object>) map.clone();
return newSet;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
//向对象输出流中写入当前的set
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
//方法写入当前类的非静态和非瞬态字段写入此流
s.defaultWriteObject();
// Write out HashMap capacity and load factor
s.writeInt(map.capacity());
s.writeFloat(map.loadFactor());
// Write out size
s.writeInt(map.size());
// Write out all elements in the proper order.
for (E e : map.keySet())
s.writeObject(e);
}
//从对象输入流中将数据反序列化到set
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic
s.defaultReadObject();
// Read capacity and verify non-negative.
int capacity = s.readInt();
if (capacity < 0) {
throw new InvalidObjectException("Illegal capacity: " +
capacity);
}
float loadFactor = s.readFloat();
if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
throw new InvalidObjectException("Illegal load factor: " +
loadFactor);
}
int size = s.readInt();
if (size < 0) {
throw new InvalidObjectException("Illegal size: " +
size);
}
capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f),
HashMap.MAXIMUM_CAPACITY);
SharedSecrets.getJavaOISAccess()
.checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity));
map = (((HashSet<?>)this) instanceof LinkedHashSet ?
new LinkedHashMap<E,Object>(capacity, loadFactor) :
new HashMap<E,Object>(capacity, loadFactor));
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
@SuppressWarnings("unchecked")
E e = (E) s.readObject();
map.put(e, PRESENT);
}
}
}
还有一个经常遇到的问题,为什么要重写equals和hashcode,什么时候要重写?
- 什么时候要重写?
- 向hashmap,hashset,hashtable等集合中添加元素时为了避免元素重复添加破坏集合准确性而要重写
2.为什么要同时重写equals和hashcode?
- 只重写hashcode方法:如果遇到了两个实例对象实际上是相同的,根据重写的hashcode方法计算出来的hashcode值是相同的,就根据equals方法来比较两者的内存地址,显然不同,所以就可能会添加进去重复元素
- 如果只重写equals方法:两个实例对象a(1,1),b(1,1),根据object类自带的hashcode方法计算出来的值是内存地址转换出来的整数,是不相同的(很小概率相同),jdk根据不同的hashcode,equals比较也是false,所以也可能添加进去重复元素
- 如果两个都不重写,hashcode会有很小的概率相同,实际上大多数情况下是不同的,很容易造成元素重复