Collections.binarySearch() using Collections.reverseOrder() as Comparator returns -1

  Kiến thức lập trình


package com.core.java.collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsBinarySearch {
     public static void main(String[] args) {
         List<Integer> al = new ArrayList<Integer>();
         al.add(10);
         al.add(20);
         al.add(30);
         al.add(40);
         al.add(50);

         // The last parameter specifies the comparator
         // method used for sorting.
         int index = Collections.binarySearch(
             al, 50, Collections.reverseOrder());

         System.out.println("Found at index " + index);
 
    }
}

Above program returns search index as -1.The binarySearch should return the location of ’50’ in the List. However it returns the index as -1. Kindly help

LEAVE A COMMENT