9/10/2023 0 Comments Java collections reverseorderReverseComparator's compare() method is able to do that, since ReverseComparator's compare() method takes two Comparables, and Integers are Comparables. The only thing that a Comparator needs to do is have a method compare() that takes two Integers. However, generics are erased at runtime (that's why the cast is "unchecked" - it is not possible to check it at runtime), so it won't cause any exceptions as long as using a ReverseComparator as a Comparator won't lead to any invalid assumptions at runtime. This unchecked cast is theoretically "incorrect" because ReverseComparator is not actually a Comparator for any T other than Comparable (and basically nobody ever implements Comparable, so it is basically always "incorrect"). ReverseComparator.REVERSE_ORDER is declared as some dummy type of comparator (it happens to be Comparator>, but it doesn't really matter it could be Comparator for all we care), and then inside the Collections.reverseOrder() method it does an unchecked cast of ReverseComparator.REVERSE_ORDER into the right type of comparator that it wants to return ( Comparator). But how can Collections.reverseOrder() return this no matter what T is? For example, it is not possible for something to be Comparator and Comparator at the same time. In the implementation of the library you are looking at, it has a single global comparator instance, ReverseComparator.REVERSE_ORDER. As for how the Collections.reverseOrder() gets a value of the type Comparator, that's an internal implementation detail of the library. It might, for example, infer T = Integer, so the Collections.reverseOrder() call will return a Comparator (or it is also valid to infer T = Object, so that Collections.reverseOrder() will return a Comparator it doesn't matter either way). The compiler sees that you want the Collections.reverseOrder() method to return the type Comparator, so it infers the T in the call to Collections.reverseOrder() that will make it return a Comparator. Checkout for comparison logic in compareTo() method.The variable comparator has type Comparator (or Comparator it doesn't matter for our purposes). In this case, implement the Comparator interface in the custom class.įor example, the domain object Employee has default sorting on the name field. We may require to sort a list of custom objects which can have their own sorting logic. List names =Īrrays.asList("Alex", "Charles", "Brian", "David") Ĭollections.sort(names, Collections.reverseOrder()) ġ.2. Java program to sort a list of strings lexicographically (in the dictionary order).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |