java.util.HashSet實現了Set接口,由一個哈希表(實際上是一個HashMap實例)支持。它不保證集合的迭代順序;特別是,它不保證順序隨時間保持不變。這個類允許null元素。HashSet實現Set接口,而Set接口繼承
Collection,而HashMap實現Map接口,不繼承Collection。
HashSet 集合不允許存儲相同的元素, 它底層實際上使用 HashMap 來存儲元素的, 不過關注的只是key元素, 所有 value元素默認爲 Object類對象。
類名
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
變量
private transient HashMap<E,Object> map;
// 與備份映射中的對象關聯的虛擬值
private static final Object PRESENT = new Object();
從變量中我們可以看出,HashSet的實現其實就是HashMap,HashMap存儲的是key-value,而HashSet是將值存在key上,value保存默認值Object。
add
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
從add方法上我們也可以看出HashSet是把值存儲到key上。
實例
HashSet<String> hashSet = new HashSet<>();
hashSet.add("a");
hashSet.add("b");
hashSet.add("c");
for (String s : hashSet) {
System.out.println(s);
}
HashSet<Student> students = new HashSet<>();
students.add(new Student("1", "java"));
students.add(new Student("2", "css"));
students.add(new Student("3", "html"));
for (Student s : students) {
System.out.println(s);
}
源碼(JDK1.8)
package java.util;
import java.io.InvalidObjectException;
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;
// 與備份映射中的對象關聯的虛擬值
private static final Object PRESENT = new Object();
/**
* 構造一個新的空集合.
*/
public HashSet() {
map = new 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);
}
/**
* 返回此集合中元素的迭代器。元素不按特定順序返回.
*/
public Iterator<E> iterator() {
return map.keySet().iterator();
}
/**
* set中元素個數
*/
public int size() {
return map.size();
}
/**
* 如果set中沒有元素則返回true
*/
public boolean isEmpty() {
return map.isEmpty();
}
/**
* 包含特定值則返回true
*/
public boolean contains(Object o) {
return map.containsKey(o);
}
/**
* 如果指定的元素不存在,則將其添加到此集
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
/**
* 如果指定的元素存在,則從該集中刪除該元素
*/
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
/**
* 刪除set中所有元素
*/
public void clear() {
map.clear();
}
/**
* 返回此HashSet實例的淺層副本:元素本身未被克隆
*/
@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);
}
}
/**
* 將此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);
}
/**
* 從流重新構造HashSet實例
*/
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);
}
// Read load factor and verify positive and non NaN.
float loadFactor = s.readFloat();
if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
throw new InvalidObjectException("Illegal load factor: " +
loadFactor);
}
// Read size and verify non-negative.
int size = s.readInt();
if (size < 0) {
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);
// Create backing 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.
for (int i=0; i<size; i++) {
@SuppressWarnings("unchecked")
E e = (E) s.readObject();
map.put(e, PRESENT);
}
}
/**
* 在這個集合的元素上創建late-binding和fail-fast
*/
public Spliterator<E> spliterator() {
return new HashMap.KeySpliterator<E,Object>(map, 0, -1, 0, 0);
}
}
更多精彩內容請關注微信公衆號: