Set
Set继承自Collection
接口,用于存储无序元素,值不能重复。自定义类要使用Set的时候,需要重写hashcode
方法和equals
方法。
1. HashSet
HashSet是基于HashMap实现的:
成员变量:
private transient HashMap<E, Object> map;
private static final Object PRESENT = new Object();
构造函数:
public HashSet() {
this.map = new HashMap();
}
Add方法
public boolean add(E e) {
return this.map.put(e, PRESENT) == null;
}
Contains方法:
public boolean contains(Object o) {
return this.map.containsKey(o);
}
Remove方法
public boolean remove(Object o) {
return this.map.remove(o) == PRESENT;
}
2. TreeSet
TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>
继承自AbstractSet
,实现了NavigableSet
,实现了元素有序。
成员变量:
private transient NavigableMap<E, Object> m;
private static final Object PRESENT = new Object();
构造函数:
public TreeSet() {
this((NavigableMap)(new TreeMap()));
} // 和TreeMap有关
Add方法
public boolean add(E e) {
return this.m.put(e, PRESENT) == null;
}
Contains方法:
public boolean contains(Object o) {
return this.map.containsKey(o);
}
Remove方法
public boolean remove(Object o) {
return this.m.remove(o) == PRESENT;
}