I use the binarySearch () method to find the position of an item in a list. And I do not understand why the index is -6. I see that the item is in position 1 after sorting in descending order. Can someone tell me why I see position -6? Thank!
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test
{
public static void main(String[] args)
{
List<Integer> al = new ArrayList<>();
al.add(100);
al.add(30);
al.add(10);
al.add(2);
al.add(50);
Collections.sort(al, Collections.reverseOrder());
System.out.println(al);
int index = Collections.binarySearch(al, 50);
System.out.println("Found at index " + index);
}
}
Output: [100, 50, 30, 10, 2]
Found at index -6
source
share