打开Set接口的源码:
public interface Set<E> extends Collection<E> { int size();正如上文所说,没有新定义额外的方法。 打开HashSet源码: public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable { // HashSet是使用HashMap实现的 private transient HashMap<E,Object> map; // 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<>(); } /** * Adds the specified element to this set if it is not already present. * More formally, adds the specified element <tt>e</tt> to this set if * this set contains no element <tt>e2</tt> such that * <tt>(e==null ? e2==null : e.equals(e2))</tt>. * If this set already contains the element, the call leaves the set * unchanged and returns <tt>false</tt>. * * @param e element to be added to this set * @return <tt>true</tt> if this set did not already contain the specified * element */ public boolean add(E e) { return map.put(e, PRESENT)==null; } 好了,HashSet的实现比较简单,就是HashMap的简单操作,把对象作为Key值赋给Map对象,value使用PRESENT。另外,set没有get方法取值,只能用迭代器遍历查询。 package com.ws.list; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class testiterator { public static void main(String[] args) { Set set=new HashSet(); set.add("aaa"); set.add("aab"); Iterator iterator=set.iterator(); while (iterator.hasNext()){ String str = (String) iterator.next(); System.out.println(str); } for (Iterator iterator2=set.iterator();iterator2.hasNext();){ String str = (String) iterator2.next(); System.out.println(str); } } }