public interface Set<E> extends Collection<E> |
Set和List一樣都是繼承自Collection接口的,已知的實現類有:AbstractSet、HashSet、LinkedHashSet、TreeSet、CopyOnWriteArraySet。
Set中的元素是不可重複,且無序的,元素在Set中的位置是由該元素的hashCode決定的,而且與List一樣,null值是允許存在,但僅有一個。
另外Set集合中的去重是和hashCode和equals方法直接相關的,如對象A、B都重寫了hashCode和equals方法,重寫後的hashCode和equals方法是相同的,那麼A、B是不能同時放入Set集合中的。
AbstractSet
public abstract class AbstractSet<E> extends AbstractCollection<E> implements Set<E> |
AbstractSet是屬於一個抽象類,繼承了AbstractCollection,實現了Set集合,看一下其中的源碼會發現,這個類並沒有定義什麼內容,只定義了3個方法,其作用應該就是作爲一箇中層,未來擴展時使用。
/** * 比較 */ public boolean equals(Object o) { //相同對象之間返回true if (o == this) return true;
//不是Set類型的直接返回false if (!(o instanceof Set)) return false;
Collection<?> c = (Collection<?>) o;
//大小不一樣的返回false if (c.size() != size()) return false; try { //當前集合是否包含待比較的對象集合,包含就返回true,不包含就返回false return containsAll(c); } catch (ClassCastException unused) { return false; } catch (NullPointerException unused) { return false; } }
/** * 把所有hashCode的值相加返回 */ public int hashCode() { int h = 0; Iterator<E> i = iterator(); while (i.hasNext()) { E obj = i.next(); if (obj != null) h += obj.hashCode(); } return h; }
/** * 刪除集合中的所有元素 * @param c * @return boolean */ public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); boolean modified = false;
//如果集合個數大於指定集合c的元素個數,則遍歷集合c並刪除現有集合相同的元素 if (size() > c.size()) { for (Iterator<?> i = c.iterator(); i.hasNext(); ) modified |= remove(i.next());
//如果集合的個數小於指定集合c的元素個數,則遍歷集合c,並刪除現有集合中相同的元素 } else { for (Iterator<?> i = iterator(); i.hasNext(); ) { if (c.contains(i.next())) { i.remove(); modified = true; } } } return modified; } |