I have following class
class A implements Comparable<A> {
private String name;
public A(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public int compareTo(A o) {
return o.getName().compareTo(this.name);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
A a = (A) o;
return name.equals(a.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
Now my understanding is that following code should produce some class name or null but not IllegalStateException as stated in the java document which says
If this Spliterator's source is SORTED by a Comparator, returns that Comparator. If the source is SORTED in natural order, returns null. Otherwise, if the source is not SORTED, throws IllegalStateException.
List<A> arrayList = new ArrayList<>();
arrayList.add(new A("Y"));
arrayList.add(new A("G"));
arrayList.add(new A("J"));
arrayList.add(new A("A"));
arrayList.add(new A("Z"));
arrayList.sort(A::compareTo);
Comparator<? super A> comparator = arrayList.spliterator().getComparator();
System.out.println(comparator);
EDIT 2
I believe i am not able to make you understand what i am looking for. Take this as example:
SortedSet<String> set = new TreeSet<>( Collections.reverseOrder() );
set.add("A");
set.add("D");
set.add("C");
set.add("B");
System.out.println(set);
System.out.println(set.spliterator().getComparator());
This outputs as
[D, C, B, A]
java.util.Collections$ReverseComparator@7852e922
Now Collections.reverseOrder() is just an implementation of Comparator
Since this is producing the right answer, my expectation from my code is also it should output a class name like above.
So what is that I am not doing right ?
While the characteristics of a
Spliteratormay reflect the current contents of a collection, they are usually depending on the type of the source collection only. So all standardListimplementations never report theSORTEDcharacteristic, even when their elements happen to be currently sorted, whereas allSortedSetimplementations always report theSORTEDcharacteristic.You may rarely need to use this method on your own. Data processing APIs, like the
StreamAPI may use the characteristics behind the scenes, to optimize the execution. For example, thesortedoperation of aStreammay get skipped when it detects that the data is already sorted. But to name a less obvious example,distinctmay work differently when the data is sorted by the element type’s natural order.Further, the state of a stream pipeline may serve as an example of a case, where the characteristics are not determined by the type:
Normally, you wouldn’t use this API to get the comparator of a collection you created yourself, as you already know the comparator. But there are cases where a spliterator has a comparator not originating from your code (directly):