Consider the following code .
List<Integer> list = new Random().ints(10,1,50).boxed().collect(Collectors.toList());
list.sort(Comparator.naturalOrder());
System.out.println(list);
System.out.print("Enter key :");
Scanner sc = new Scanner(System.in);
int key = sc.nextInt();
int ans = Collections.binarySearch(list, key);
String result = String.format("ans = %d, list.at(ans*-1) = %d , lower bond = %d , upper bound = %d ", ans,list.get(ans*-1),list.get(ans*-1 -2 ) ,
list.get(ans * -1 -1));
System.out.println(result);
I was working on binarySearch method given by Collections class. When key does not present in list, it gives these weird numbers in negative. I mapped them to their lower bound and upper bound. I worked on several examples and always got it right.
see this
For every input I have given it return correct upper bound and lower bound inside the list. Can Anyone explain to me ? Whats happening inside the hood ?