Java中的Set实现

Set接口

public interface Set<E> extends Collection<E> {

}

HashSet

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();
	
	public HashSet() {
        map = new HashMap<>();
    }
	
	//该构造函数是设计给LinkedHashSet使用的
	HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }

	public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
}

不难发现,HashSet的实现是基于HashMap的。

LinkedHashSet

public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, java.io.Serializable {

	public LinkedHashSet() {
        super(16, .75f, true);
    }

}

TreeSet

public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, java.io.Serializable{
	private transient NavigableMap<E,Object> m;
	private static final Object PRESENT = new Object();
	
	//TreeSet的底层是一个TreeMap
	public TreeSet() {
        this(new TreeMap<E,Object>());
    }
	
	TreeSet(NavigableMap<E,Object> m) {
        this.m = m;
    }
}

你可能感兴趣的:(java)