java使用binarySearch在ArrayList中查找对象
我在ArrayList中搜索对象时遇到问题
这是我目前的代码:
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;
}
这是我的测试:
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);
}
程序总是返回-1,这意味着它永远找不到正在搜索的对象?你看到什么错误了吗?还是我的搜索测试不正确
# 1 楼答案
你将
comp
与pos
进行比较,这就像将Comparable
(在本例中,aString
)与Integer
进行比较:相反,您应该检索列表中
pos
索引中的元素,并使用该元素进行比较: