问题
(1) ConcurrentSkipListSet的底层是ConcurrentSkipListMap吗?
(2) ConcurrentSkipListSet是线程安全的吗?
(3) ConcurrentSkipListSet是有序的吗?
(4) ConcurrentSkipListSet和之前讲的设置有何不同?
简介
ConcurrentSkipListSet底层是通过ConcurrentNavigableMap来实现的,它是一个有序的线程安全的集合。
源码分析
它的源码比较简单,跟通过地图实现的集基本是一致,只是多了一些取最近的元素的方法。
为了保持专栏的完整性,我还是贴一下源码,最后会对组的整个家族作一个对比,有兴趣的可以直接拉到最下面。
<代码类="语言java ">//实现了NavigableSet接口,并没有所谓的ConcurrentNavigableSet接口 公开课ConcurrentSkipListSet扩展AbstractSet 实现NavigableSet 可克隆,io。可序列化的{ 私有静态最终长serialVersionUID=-2479143111061671589 l;//存储使用的地图 私人最终ConcurrentNavigableMap m;//初始化 公共ConcurrentSkipListSet () { m=新ConcurrentSkipListMap (); }//传入比较器 公共ConcurrentSkipListSet (Comparator<?超级E>比较器){ m=新ConcurrentSkipListMap (比较); }//使用ConcurrentSkipListMap初始化地图//并将集合c中所有元素放入到映射中 公共ConcurrentSkipListSet (Collection<?E>延伸;c) { m=新ConcurrentSkipListMap (); addAll (c); }//使用ConcurrentSkipListMap初始化地图//并将有序组中所有元素放入到映射中 公共ConcurrentSkipListSet (SortedSet s) { m=新ConcurrentSkipListMap (s.comparator ()); addAll(年代); }//ConcurrentSkipListSet类内部返回子组时使用的 ConcurrentSkipListSet (ConcurrentNavigableMap 米){ 这一点。m=m; }//克隆方法 公共ConcurrentSkipListSet 克隆(){ 尝试{ @SuppressWarnings (“unchecked”) ConcurrentSkipListSet 克?(ConcurrentSkipListSet (m)); 返回克隆; }捕捉(CloneNotSupportedException e) { 把新InternalError (); } }/* - - - - - - - - - - - - - - - - -集合操作- - - - - - - - - - - - - - - *///返回元素个数 公共int大小(){ 返回m.size (); }//检查是否为空 公共布尔isEmpty () { 返回m.isEmpty (); }//检查是否包含某个元素 公共逻辑包含(对象o) { 返回m.containsKey (o); }//添加一个元素//调用地图的putIfAbsent()方法 公共逻辑加(E E) { 返回m。putIfAbsent (e, Boolean.TRUE)==零; }//移除一个元素 公共逻辑删除对象(o) { 返回m。删除(o, Boolean.TRUE); }//清空所有元素 公共空间clear () { m.clear (); }//迭代器 公共Iterator iterator () { .iterator返回m.navigableKeySet () (); }//降序迭代器 公共Iterator descendingIterator () { .iterator返回m.descendingKeySet () (); }/* - - - - - - - - - - - - - - - - -套抽象覆盖- - - - - - - - - - - - - - - *///比较相等方法 公共布尔=(对象o) {//覆盖套抽象版本避免调用大小() 如果(o==) 返回true; 如果(!(o instanceof集)) 返回错误; Collection<?比;c=o (Collection<?祝辞); 尝试{//这里是通过两次两层为循环来比较//这里是有很大优化空间的,参考上篇文章CopyOnWriteArraySet中的彩蛋 返回containsAll (c),,c.containsAll(这个); }捕捉(ClassCastException未使用){ 返回错误; }捕捉(未使用NullPointerException) { 返回错误; } }//移除集合c中所有元素 公共布尔removeAll (Collection<?比;c) {//覆盖套抽象版本,以避免不必要的调用大小() 布尔修改=false; (对象e: c) 如果删除(e)) 修改=true; 返回修改; }/* - - - - - - - - - - - - - - - - -关系操作- - - - - - - - - - - - - - - *///小于e的最大元素 公共E低(E E) { 返回m.lowerKey (e); }//小于等于e的最大元素 公共E层(E E) { 返回m.floorKey (e); }//大于等于e的最小元素 公共E上限(E E) { 返回m.ceilingKey (e); }//大于e的最小元素 公众E更高(E E) { 返回m.higherKey (e); }//弹出最小的元素 公共E pollFirst () { Map.Entry e=m.pollFirstEntry (); 返回(e==null) ?空:e.getKey (); }//弹出最大的元素 公共E pollLast () { Map.Entry e=m.pollLastEntry (); 返回(e==null) ?空:e.getKey (); }/* - - - - - - - - - - - - - - - - - SortedSet操作- - - - - - - - - - - - - - - - *///取比较器 公共Comparator<?超级E>比较器(){ 返回m.comparator (); }//最小的元素 公共E第(){ 返回m.firstKey (); }//最大的元素 公共E去年(){ 返回m.lastKey (); }//取两个元素之间的子集合 公共NavigableSet 死磕java集合之ConcurrentSkipListSet源码分析,集大汇总