Collection接口的子接口——Set接口

  https://docs.oracle.com/javase/8/docs/api/java/util/Set.html

  

  public interface Set<E>  extends Collection<E>

  E是Set管理的元素类型。

  父接口:Collection<E>, Iterable<E>

  子接口:NavigableSet<E>, SortedSet<E>

  实现类:EnumSet,HashSet,LinkedHashSet,TreeSet

  一、简介

  顾名思义,Set接口是对数学集的抽象建模。

  Set是一个不包含重复元素的容器,允许元素为null值(最多存在一个null元素)。Set没有强制其中的元素必须有序~

  与上面呼应,Set接口规定,构造函数不能创建包含重复元素的对象。

  注意,如果是可变对象(mutable objects)成为了Set中的元素,那么当可变的对象的修改影响到了equals比较的结果,这时Set的行为是不明确的。

  Set不允许把自身当作一个元素。

  Set的不同实现类会对元素的类型有不同的限制,往其中添加不合格元素or查询不合格元素的存在时,会抛出异常或者报错。

  二、方法(和父接口Collection中的基本一致)

  1、int size()

  2、boolean isEmpty()

  3、boolean contains(Object o)

  4、Iterator<E> iterator()

  Returns an iterator over the elements in this set.

  The elements are returned in no particular order (unless this set is an instance of some class that provides a guarantee).

  5、Object[] toArray()

  返回一个包含Set中所有元素的数组。

  如果Set本身制定了元素的顺序(它的迭代器中的元素是有序的),那么这个方法返回元素的顺序也应该一致。

  返回的数组是“安全的”,因为没有任何引用变量指向它,它的引用由这个Set保留,这意味着这个方法必须分配一个新的数组,即使这个set集合本身就是数组。而调用者则可以自由修改返回得到的数组。(这里返回的是新分配的数组的引用)

  这个函数充当了以数组为基础的API和以集合为基础的API之间的桥梁。

  6、<T> T[ ] toArray(T[ ] a)

  和上面功能一致,但是细节不一样,要求返回指定类型的数组。

  7、boolean add(E e)

  如果Set集合中不包含e元素,则添加进集合。(可选操作)

  这个函数和Set对构造函数的规定,确保了Set集合中不会包含重复的元素。

  但是,Set只是一个接口,具体的实现类可以对元素的类型做不同的限制(如是否允许null值)。

  8、boolean remove(Object o)

  如果指定元素包含在Set集合中,删除并返回true。(可选操作)

  9、boolean containsAll(Collection<?> c)

  判断集合c是不是这个集合的子集。

  10、boolean addAll(Collection<? extends E> c)

  把自己没有而集合c中的有的元素添加进来(a U c)。(可选操作)

  本操作进行时,如果集合c发生了改变,结果不可预知。

  11、boolean removeAll(Collection<?> c)

  A-C(可选操作)

  12、boolean retainAll(Collection<?> c)

  保留两个集合的交。(可选操作)

  13、void clear()

  集合清空。(可选操作)

  14、boolean equals(Object o)

  Compares the specified object with this set for equality. Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.

  15、int hashCode()

  Returns the hash code value for this set. The hash code of a set is defined to be the sum of the hash codes of the elements in the set, where the hash code of a null element is defined to be zero. This ensures that s1.equals(s2) implies that s1.hashCode()==s2.hashCode() for any two sets s1 and s2, as required by the general contract of Object.hashCode().

  16、default Spliterator<E> spliterator()

  Creates a Spliterator over the elements in this set. The Spliterator reports Spliterator.DISTINCT. Implementations should document the reporting of additional characteristic values.

  

  

原文地址:https://www.cnblogs.com/bigbigbigo/p/8564445.html