Map是Java容器的又一长老,映射表(也称为关联数组),基本思想是维护一对键-值对,通过键来查找值。
标准Java类库中包含Map的几种基本实现,包括:HashMap,TreeMap,LinkedHashMap,WeakHashMap,ConcurrentHashMap,IdentityHashMap,他们之间各自有一个自己的特性。
Set,大概看了一些Set的实现类,如HashSet,TreeSet,发现Set其实是基于Map来搭建的,如果你了解了Map的结构那你就知道Set是怎么回事儿了,看了jdk的源码就会知道,原来所谓的Set都是由Map构成的,只不过Map是通过<Key,Value>的形式存储,而Set中的Value都指向同一个对象,jdk中给他起名叫PRESENT(替代者),这样就不会造成太大的空间浪费了。
HashSet的实现
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; //内部结构的维护使用的HashMap // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object(); /** * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has * default initial capacity (16) and load factor (0.75). */ public HashSet() { map = new HashMap<E,Object>(); }……而LinkedHashSet继承自HashSet,
再看一下TreeSet
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, java.io.Serializable { /** * The backing map. */ private transient NavigableMap<E,Object> m; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object(); /** * Constructs a set backed by the specified navigable map. */ TreeSet(NavigableMap<E,Object> m) { this.m = m; }