簡體   English   中英

使用binarySearch在ArrayList中查找Object

[英]Using binarySearch to look for Object in ArrayList

我在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,這意味着它永遠不會找到它正在搜索的對象? 你看到有什么錯誤嗎? 或者我是否錯誤地測試了搜索?

你將comppos進行comp ,就像將Comparable (在本例中為String )與Integer

int comparison = comp.compareTo(pos);

相反,您應該檢索列表中pos索引中的元素並使用該元素進行比較:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM