Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ConcurrentSkipListSet.contains requires comparator and not equals

I am using ConcurrentSkipListSet and using contains method.

As per JAVA doc for contains method

Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that o.equals(e).

But as per my test , it appears that equals method is not used but rather Comparator is mandatory. Please help me understand this anomaly between JAVA spec and implementation

ConcurrentSkipListSet

/** * If using comparator, return a ComparableUsingComparator, else * cast key as Comparable, which may cause ClassCastException, * which is propagated back to caller. */ private Comparable comparable(Object key)

at java.util.concurrent.ConcurrentSkipListMap.comparable(ConcurrentSkipListMap.java:663) at java.util.concurrent.ConcurrentSkipListMap.doGet(ConcurrentSkipListMap.java:821) at java.util.concurrent.ConcurrentSkipListMap.containsKey(ConcurrentSkipListMap.java:1608)

I am using Oracle JDK 7

like image 647
Amrish Pandey Avatar asked Jun 15 '16 17:06

Amrish Pandey


People also ask

What is ConcurrentSkipListSet in Java?

The ConcurrentSkipListSet class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractSet class. It provides a scalable and concurrent version of NavigableSet in Java. The implementation of ConcurrentSkipListSet is based on ConcurrentSkipListMap.

What is ConcurrentSkipListMap?

The ConcurrentSkipListMap is a scalable implementation of ConcurrentNavigableMap. All the elements are sorted based on natural ordering or by the Comparator passed during it's construction time.

Which class provides methods to return iterators in ascending or descending order?

The iterator() method of java. util. concurrent. ConcurrentSkipListSet is an in-built function in Java which is used to return an iterator over the elements in this set in ascending order.


1 Answers

I think there are two questions/concerns, (1) Why does the contains require a Comparator or Comparable. (2) The Javadoc says it will use the equals method.

  1. A ConcurrentSkipListSet is a navigable ordered collection so all elements either must maintain a natural order, or you must specify a comparator.
  2. I think the Javadoc is stated incorrectly, or at the very least it is misleading. Under the hood, the CSLS will delegate to a ConcurrentSkipListMap.containsKey so it, right now, does not control the contains implementation. That said, I think there can be an argument to clarify the javadocs.

EDIT: There is also a throws doc for the fact these objects aren't comparable

ClassCastException - if the specified element cannot be compared with the elements currently in this set

like image 65
John Vint Avatar answered Oct 06 '22 05:10

John Vint