在对象中实现二进制搜索

时间:2009-05-23 17:10:29

标签: java search collections binary-search

有没有办法在带有对象的ArrayList中实现二进制搜索?在此示例中,ArrayList将使用字段'id'进行排序。

class User{
 public int id;
 public string name;
}

ArrayList<User> users = new ArrayList<User>();

sortById(users);

int id = 66
User searchuser = getUserById(users,id);

如果我应该使用二进制搜索返回具有指定id的用户,那么“User getUserById(ArrayList users,int userid)”如何?这甚至可能吗?

5 个答案:

答案 0 :(得分:49)

The Java Tutorials的Object Ordering文章有一个编写自己的Comparator的例子,以便对自定义类型进行比较。

然后,ArrayList(或任何其他List),要查找的密钥以及Comparator可以传递到Collections.binarySearch方法。

以下是一个例子:

import java.util.*;

class BinarySearchWithComparator
{
  public static void main(String[] args)
  {
    // Please scroll down to see 'User' class implementation.
    List<User> l = new ArrayList<User>();
    l.add(new User(10, "A"));
    l.add(new User(20, "B"));
    l.add(new User(30, "C"));

    Comparator<User> c = new Comparator<User>() {
      public int compare(User u1, User u2) {
        return u1.getId().compareTo(u2.getId());
      }
    };

    // Must pass in an object of type 'User' as the key.
    // The key is an 'User' with the 'id' which is been searched for.
    // The 'name' field is not used in the comparison for the binary search,
    // so it can be a dummy value -- here it is omitted with a null.
    //
    // Also note that the List must be sorted before running binarySearch,
    // in this case, the list is already sorted.

    int index = Collections.binarySearch(l, new User(20, null), c);
    System.out.println(index);    // Output: 1

    index = Collections.binarySearch(l, new User(10, null), c);
    System.out.println(index);    // Output: 0

    index = Collections.binarySearch(l, new User(42, null), c);
    System.out.println(index);    // Output: -4
                                  // See javadoc for meaning of return value.
  }
}

class User {
  private int id;
  private String name;

  public User(int id, String name) {
    this.id = id;
    this.name = name;
  }

  public Integer getId() {
    return Integer.valueOf(id);
  }
}

答案 1 :(得分:6)

您也可以将比较器放在User类中:

public class User implements Comparable<User>, Comparator<User>
{
  public User(int id, String name)
  {
    this.id = id;
    this.name = name;
  }
  @Override
  public int compareTo(User u)
  {
    return id - u.getID();
  }
  @Override
  public int compare(User u1, User u2)
  {
    return u1.getID() - u2.getID();
  }

  public int getID() { return id; }
  public String getName() { return name; }
  private int id;
  private String name;
}

然后,您将对名为users的ArrayList执行以下操作:

ArrayList<User> users = new ArrayList<User>();
users.add(new User(3, "Fred"));
users.add(new User(42, "Joe"));
users.add(new User(5, "Mary"));
users.add(new User(17, "Alice"));

Collections.sort(users);
int index = Collections.binarySearch(users, new User(5, null));
if(index >= 0)
  System.out.println("The user name of id 5 is: "+users.get(index).getName());
else
  System.out.println("ID 5 is not in the list");

答案 2 :(得分:5)

Collections.binarySearchComparator一起使用。

答案 3 :(得分:2)

import java.util.Collections;
Collections.binarySearch(users, id);

答案 4 :(得分:1)

您应该仅对已排序的ArrayList使用binarySearch方法。首先对ArraList进行排序并使用相同的比较器引用(您用于排序)来执行binarySearch操作。