使用binarySearch在ArrayList中查找Object

时间:2014-02-12 14:36:10

标签: java binary-search

我在搜索ArrayList中的Object时遇到问题。

到目前为止,这是我的代码:

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 个答案:

答案 0 :(得分:2)

您将comppos进行比较,就像比较Comparable(在这种情况下,String)与Integer

int comparison = comp.compareTo(pos);

相反,您应该检索列表中pos索引中的元素,并使用该元素进行比较:

int comparison = comp.compareTo(list.get(pos));