gpt4 book ai didi

java - 在 ArrayList 中搜索对象

转载 作者:行者123 更新时间:2023-12-02 08:22:28 25 4
gpt4 key购买 nike

我将对象存储在 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。那怎么可能呢?

最佳答案

你可以使用

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

新的POJOSortableContacts只是一个充当键的虚拟对象。

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

关于java - 在 ArrayList 中搜索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5216894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com