2014-02-12 66 views
0

我在搜索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,这意味着它永远不会发现它的搜索对象?你有没有看到任何错误?或者我测试搜索不正确?

+0

'new String(“February”)'是无稽之谈。只要写'“二月”'。通过传递另一个String来构造'String'是没有用的。 – Holger

回答

2

你对pos这就好比是一个比较Comparable(在这种情况下,String)与Integer比较comp

int comparison = comp.compareTo(pos); 

你应该,而是检索元素pos索引列表并使用该元素进行比较:

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

当然,这是有道理的! 但改变后,我仍然收到-1,即使在这种情况下,索引应该是0? – theOGloc

+0

@theOGloc我刚刚复制并粘贴了您的代码和我的更改并打印* 2月份位于index0 *。将密钥更改为“June”并打印*六月份位于index2 *处。确保保存更改,重新编译并重新运行测试。 –

+0

当然可以。我意识到我有一个自定义不完整的ArrayList类,它给了我错误的列表大小。谢谢您的帮助! – theOGloc