Java 集合框架(Set 接口)

2018-11-12  本文已影响0人  6ea566508d0d

Set 接口简介

对于 Set 接口,Java的官方文档这样提到:

A Set that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements.

可以简单理解为:

然后讲了下关于 Set 的实现:

The Java platform contains three general-purpose Set implementations: HashSet, TreeSet, and LinkedHashSet. HashSet, which stores its elements in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration. TreeSet, which stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet. LinkedHashSet, which is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order). LinkedHashSet spares its clients from the unspecified, generally chaotic ordering provided by HashSet at a cost that is only slightly higher.

简单的来说一下:

性能比较:HashSet > LinkedHashSet > TreeSet
(虽然文档中提到,LinkedHashSet 的性能是接近于 HashSet 的)


Set 接口相关操作

前面也已经提到,Set 接口的方法都是继承自 Collection 接口的,故其操作和 Collection 接口一致。这些操作包括:
    基础操作批量操作数组操作、以及 JDK1.8 后提供的聚合操作

继承自 Collection 接口的操作:

int size() // 返回集合中元素的个数
boolean isEmpty() // 判断集合是否存在元素
boolean contains(Object element) // 判断集合是否包含
boolean add(E element) // 添加元素
boolean remove(Object element) // 删除元素
Iterator<E> iterator() // 获取该集合的迭代器
boolean containsAll(Collection<?> c) // 包含
boolean addAll(Collection<? extends E> c) //并集
boolean removeAll(Collection<?> c) // 差集
boolean retainAll(Collection<?> c) // 交集
void clear() // 清空
Object[] toArray() // 集合转换为数组
<T> T[] toArray(T[] a)  // 集合转换为指定类型的数组

更多参考:The Set Interface (The Java™ Tutorials > Collections > Interfaces)

上一篇 下一篇

猜你喜欢

热点阅读