I have a problem with searching for an Object in an ArrayList.
This is my code so far:
public static int binarySearch( ArrayList list, Object key ) {
Comparable comp = (Comparable)key;
int res = -1, min = 0, max = list.size() - 1, pos;
while( ( min <= max ) && ( res == -1 ) ) {
pos = (min + max) / 2;
int comparison = comp.compareTo(pos);
if( comparison == 0)
res = pos;
else if( comparison < 0)
max = pos - 1;
else
min = pos + 1;
}
return res;
}
And this is my testing:
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(new String("February"));
list.add(new String("January"));
list.add(new String("June"));
list.add(new String("March"));
System.out.println(list);
Object obj = new String("February");
int index = binarySearch(list, obj);
System.out.println(obj + " is at index" + index);
}
The program always returns -1, which means that it never finds the object it's searching for? Do you see any error? Or am I testing the search incorrectly?
new String("February")is nonsense. Just write"February". There is no use for constructing aStringby passing anotherString.