See this code:
package learningjava;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Java{
public static void main(String args[]) {
List obj = new ArrayList();
obj.add(2);
obj.add(4);
obj.add(6);
obj.add(1);
int bs = Collections.binarySearch(obj,6);
System.out.println(bs);
}
}
Here I am using binarySearch method in Collections class. I am using it to find the position of 6 in this list. Here it is returning 2 which is correct.
But if I try to find the postion of 1 in this list it is returning -1.
package LearningJava;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Java{
public static void main(String args[]) {
List obj = new ArrayList();
obj.add(2);
obj.add(4);
obj.add(6);
obj.add(1);
int bs = Collections.binarySearch(obj,1);
System.out.println(bs);
}
}
The output is -1.
Why is it returning -1 instead of 3. The problem is only with 1. If I try to find the position of other numbers, it is working correctly.