我在搜索ArrayList中的对象时遇到问题。使用binarySearch在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,这意味着它永远不会发现它的搜索对象?你有没有看到任何错误?或者我测试搜索不正确?
'new String(“February”)'是无稽之谈。只要写'“二月”'。通过传递另一个String来构造'String'是没有用的。 – Holger