而添加多个元素,继承自 AbstractCollection 抽象类,通过 #addAll(Collection<? extends E> c) 方法,代码如下:
// AbstractCollection.java
publicbooleanaddAll(Collection<? extends E> c){ boolean modified = false; // 遍历 c 集合,逐个添加 for (E e : c) if (add(e)) modified = true; return modified; }
在方法内部,会逐个调用 #add(E e) 方法,逐个添加单个元素。
6. 移除单个元素
#remove(Object key) 方法,移除 key 对应的 value ,并返回该 value 。代码如下:
// 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.getJavaObjectInputStreamAccess() .checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity)); // 不知道作甚,哈哈哈。
// 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); } }