(五)并发-集合SET(ConcurrentSkipListSet)

103 阅读2分钟

继承关系

图片.png 继承AbstractSet说明是个Set集合,实现了NavigableSet接口,而NavigableSet继承自SortedSet,说明集合是有序结合,ConcurrentSkipListSet底层维护了一个ConcurrentNavigableMap,初始化时实际上是创建了ConcurrentNavigableMap,并且使用ConcurrentNavigableMap中的Key来存储元素。

跳跃表结构

相比于普通的链表来说:

图片.png 查找20需要查找四次,对于如果存在头不得元素查找非常快,对于数据量达到一定程度并且查找的元素在链表的尾部,则查找的效率非常慢。因此为了查找效率,将链表的增加索引并提取出层级关系,增加查找效率。并且上层索引指向下层索引。

图片.png

  • 对于查找20,首先第一层索引确定往回找。
  • 第二层索引在15-25之间。确定范围
  • 依次往下查找,最终定位在原始数据的15-25范围之间。对同对比找到20

初始化

初始化主要是创建ConcurrentSkipListMap并赋值给m

private final ConcurrentNavigableMap<E,Object> m;
public ConcurrentSkipListSet()
public ConcurrentSkipListSet(Comparator<? super E> comparator)
public ConcurrentSkipListSet(Collection<? extends E> c)
public ConcurrentSkipListSet(SortedSet<E> s)

添加元素

调用add(E e)最终会调用ConcurrentSkipListMap.putIfAbsent方法进行添加,而只使用Key

public boolean add(E e) -> ConcurrentSkipListMap.putIfAbsent(K key, V value)

删除元素

//删除某个元素
public boolean remove(Object o)
//清空集合
public void clear()
//删除集合中包含的集合c元素
public boolean removeAll(Collection<?> c)

public E pollFirst()

遍历元素

遍历获取的数据为keySet集合

//获取升序的集合迭代器
public Iterator<E> iterator()
//获取降序的集合迭代器
public Iterator<E> descendingIterator()

关系方法

//获取集合中小于元素e的最大元素
public E lower(E e)
//获取集合中小于等于元素e的最大元素
public E floor(E e)
//获取集合中大于等于元素e的最小元素
public E ceiling(E e)
//获取集合中大于元素e的最小元素
public E higher(E e)
//集合中第一个值(最小值升序)
public E pollFirst() 
//集合中最后的值(最大元素升序)
public E pollLast() 

有序方法

//获取比较器
public Comparator<? super E> comparator()
//升序最小值
public E first()
//升序最大值
public E last()
//获取fromElement->toElement之间的元素
public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)
//获取集合中开始->toElement之间的元素
public NavigableSet<E> headSet(E toElement, boolean inclusive)
//获取集合中fromElement->最后之间的元素
public NavigableSet<E> tailSet(E fromElement, boolean inclusive)
//获取集合中fromElement(含)->toElement(不含)之间的元素
public NavigableSet<E> subSet(E fromElement, E toElement)
//获取第一个到toElement(不含)之间的元素
public NavigableSet<E> headSet(E toElement)
//获取从fromElement(含)-> 最后一个元素
public NavigableSet<E> tailSet(E fromElement)
//获取降序集合
public NavigableSet<E> descendingSet()
//获取切割的迭代器
public Spliterator<E> spliterator()