有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

  1. # 1 楼答案

    你将comppos进行比较,这就像将Comparable(在本例中,a String)与Integer进行比较:

    int comparison = comp.compareTo(pos);
    

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

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