在ArrayList中搜索对象

时间:2011-03-07 07:17:58

标签: java collections arraylist binary-search

我在ArrayList中存储对象,其中我的pojo为

public class POJOSortableContacts {
    private Long id;
    private String displayName;


    public POJOSortableContacts(Long id, String displayName) {

        super();
        this.id           = id;
        this.displayName  = displayName;
    }

    //Setter and Getters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    //This will be used to sectioned header.
    public String getLabel() {
        return Character.toString(displayName.charAt(0)).toUpperCase();
    }



    //Sortable categories
    //Sort by Contact name
    public static Comparator<POJOSortableContacts> COMPARE_BY_NAME = new Comparator<POJOSortableContacts>() {
        public int compare(POJOSortableContacts one, POJOSortableContacts other) {
            return one.getDisplayName().compareToIgnoreCase(other.getDisplayName());
            //return s1.toLowerCase().compareTo(s2.toLowerCase()); //it returns lower_case word first and then upper_case
        }
    };

    //Sort by id
    public static Comparator<POJOSortableContacts> COMPARE_BY_ID = new Comparator<POJOSortableContacts>() {
        public int compare(POJOSortableContacts one, POJOSortableContacts other) {
            return one.id.compareTo(other.id);
        }
    };
}

和Arraylist结构如

ArrayList<POJOSortableContacts> contactArrayList = new ArrayList<POJOSortableContacts>() 

,我想通过id从contactArrayList搜索一个对象(例如我想要一个id为20的对象),我想为此使用binarysearch。那怎么可能呢?

5 个答案:

答案 0 :(得分:1)

您可以使用

POJOSortableContacts contact = Collections.binarySearch(contactArrayList,
                                               new POJOSortableContacts(20, ""),
                                               COMPARE_BY_ID);

新的POJOSortableContacts只是一个虚拟对象,可以作为密钥。

当然,这只有在你的列表按ID开始排序时才有效 - 你不能在未排序的列表上使用二进制搜索(或者以不同方式排序的列表)。

答案 1 :(得分:1)

我建议您使用HashMap。

Map<Long,POJOSortableContacts> contactMap = new HashMap<Long,POJOSortableContacts>();

像这样填写你的contactMap:

contactMap.put(myContact.getId(), myContact);

然后搜索变得微不足道:

POJOSortableContacts myContact = contactMap.get(myID);

答案 2 :(得分:0)

为了能够使用二进制搜索,必须对您的集合进行排序。您可以每次在搜索之前对ArrayList进行排序,但这会否定使用二进制搜索的优势(您可以在未排序的列表上进行线性搜索并且仍然更快)。

答案 3 :(得分:0)

ArrayList有一个方法 - BinarySearch,它将对象作为参数进行搜索。

POJOSortableContacts contactToSearch = new POJOSortableContacts(someId, "Name");
POJOSortableContacts myContact = contactArrayList.BinarySearch(contactToSearch);    

希望这有帮助。

答案 4 :(得分:0)

稍微回避一下这个问题,如果你不能在列表中有重复项,那么使用SortedSet存储联系人可能会更好。在使用binarySearch之前不再排序......