1.创建HashSet
Set<String> set = new HashSet<>(); set.add("aaa");
2.构造方法
private transient HashMap<E,Object> map; /** * 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<>(); }
3.add方法 内部通过HashMap 保证数据不重复
public boolean add(E e) { return map.put(e, PRESENT)==null; }
TreeSet
创建TreeSet
Set<String> set = new TreeSet<>(); set.add("aaa");
构造方法
private transient NavigableMap<E,Object> m; Constructs a new, empty tree set, sorted according to the natural ordering of its elements. All elements inserted into the set must implement the Comparable interface. Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the set. If the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string element to a set whose elements are integers), the add call will throw a ClassCastException. public TreeSet() { this(new TreeMap<E,Object>()); } /** * Constructs a set backed by the specified navigable map. */ TreeSet(NavigableMap<E,Object> m) { this.m = m; }
add方法
public boolean add(E e) { return m.put(e, PRESENT)==null; }