11. 序列化writeObject(ObjectOutputStream s)
12. 反序列化readObject(ObjectInputStream s)
1. 概述
HashSet ,基于 HashMap 的 Set 实现类。在业务中,如果我们有排重的需求,一般会考虑使用 HashSet 。
在 Redis 提供的 Set 数据结构,不考虑编码的情况下,它是基于 Redis 自身的 Hash 数据结构实现的。这点,JDK 和 Redis 是相同的
2,类图
- 实现 java.util.Set 接口,并继承 java.util.AbstractSet 抽像类。
- 实现 java.io.Serializable 接口。
- 实现 java.lang.Cloneable 接口。
3. 属性
HashSet 只有一个属性,那就是 map
。代码如下:
private transient HashMap<E,Object> map;
map
的 key ,存储 HashSet 的每个 key
map
的 value ,因为 HashSet 没有 value 的需要,所以使用一个统一的 PRESENT
即可。代码如下:
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
4. 构造方法
HashSet 一共有 5 个构造方法,代码如下:
public HashSet() {
map = new HashMap<>();
}
/**
* Constructs a new set containing the elements in the specified
* collection. The <tt>HashMap</tt> is created with default load factor
* (0.75) and an initial capacity sufficient to contain the elements in
* the specified collection.
*
* @param c the collection whose elements are to be placed into this set
* @throws NullPointerException if the specified collection is null
*/
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* the specified initial capacity and the specified load factor.
*
* @param initialCapacity the initial capacity of the hash map
* @param loadFactor the load factor of the hash map
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* the specified initial capacity and default load factor (0.75).
*
* @param initialCapacity the initial capacity of the hash table
* @throws IllegalArgumentException if the initial capacity is less
* than zero
*/
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
/**
* Constructs a new, empty linked hash set. (This package private
* constructor is only used by LinkedHashSet.) The backing
* HashMap instance is a LinkedHashMap with the specified initial
* capacity and the specified load factor.
*
* @param initialCapacity the initial capacity of the hash map
* @param loadFactor the load factor of the hash map
* @param dummy ignored (distinguishes this
* constructor from other int, float constructor.)
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
- 在构造方法中,会创建 HashMap 或 LinkedHashMap 对象。
5. 添加单个元素add(E e)
add(E e)
方法,添加单个元素。代码如下:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
map
的 value 值,就是我们看到的PRESENT
。
6. 添加多个元素addAll(Collection<? extends E> c)
添加多个元素,是继承自AbstractCollection 抽象类addAll(Collection<? extends E> c)
方法,代码如下:
- 在方法内部,会逐个调用
#add(E e)
方法,逐个添加单个元素。
public boolean addAll(Collection<? extends E> c) {
boolean modified = false;
for (E e : c) // 遍历 c 集合,逐个添加
if (add(e))
modified = true;
return modified;
}
7. 移除单个元素remove(Object key)
remove(Object key)
方法,移除 key 对应的 value ,并返回该 value 。代码如下:
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
8. 查找单个元素contains(Object key)
contains(Object key)
方法,判断 key 是否存在。代码如下:
public boolean contains(Object o) {
return map.containsKey(o);
}
9. 转换成数组toArray(T[] a)
toArray(T[] a)
方法,转换出 key 数组返回。代码如下:
public Object[] toArray() {
// Estimate size of array; be prepared to see more or fewer elements
Object[] r = new Object[size()];
Iterator<E> it = iterator();
for (int i = 0; i < r.length; i++) {
if (! it.hasNext()) // fewer elements than expected
return Arrays.copyOf(r, i);
r[i] = it.next();
}
return it.hasNext() ? finishToArray(r, it) : r;
}
10. 清空clear()
clear()
方法,清空 HashSet 。代码如下:
public void clear() {
map.clear();
}
11. 序列化writeObject(ObjectOutputStream s)
writeObject(ObjectOutputStream s)
方法,序列化 HashSet 对象。代码如下:
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden serialization magic
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);
}
12. 反序列化readObject(ObjectInputStream s)
readObject(ObjectInputStream s)
方法,反序列化成 HashSet 对象。代码如下:
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic // 读取非静态属性、非 transient 属性
s.defaultReadObject();
// Read capacity and verify non-negative.
int capacity = s.readInt(); // 读取 HashMap table 数组大小
if (capacity < 0) { // 校验 capacity 参数
throw new InvalidObjectException("Illegal capacity: " +
capacity);
}
// Read load factor and verify positive and non NaN.
float loadFactor = s.readFloat(); // 获得加载因子 loadFactor
if (loadFactor <= 0 || Float.isNaN(loadFactor)) { // 校验 loadFactor 参数
throw new InvalidObjectException("Illegal load factor: " +
loadFactor);
}
// Read size and verify non-negative.
int size = s.readInt(); // 读取 key-value 键值对数量 size
if (size < 0) { // 校验 size 参数
throw new InvalidObjectException("Illegal size: " +
size);
}
// Set the capacity according to the size and load factor ensuring that
// the HashMap is at least 25% full but clamping to maximum capacity.// 计算容量
capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f),
HashMap.MAXIMUM_CAPACITY);
// Constructing the backing map will lazily create an array when the first element is
// added, so check it before construction. Call HashMap.tableSizeFor to compute the
// actual allocation size. Check Map.Entry[].class since it's the nearest public type to
// what is actually created.
SharedSecrets.getJavaOISAccess()
.checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity));
// Create backing HashMap // 创建 LinkedHashMap 或 HashMap 对象
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. // 遍历读取 key 键,添加到 map 中
for (int i=0; i<size; i++) {
@SuppressWarnings("unchecked")
E e = (E) s.readObject();
map.put(e, PRESENT);
}
}
13. 克隆clone()
clone()
方法,克隆 HashSet 对象。代码如下:
@SuppressWarnings("unchecked")
public Object clone() {
try { // 调用父方法,克隆创建 newSet 对象
HashSet<E> newSet = (HashSet<E>) super.clone();
newSet.map = (HashMap<E, Object>) map.clone(); // 可控 mao 属性,赋值给 newSet
return newSet; // 返回
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
14. 获得迭代器iterator()
iterator()
方法,获得迭代器。代码如下:
public Iterator<E> iterator() {
return map.keySet().iterator();
}