gpt4 book ai didi

java - 将 IndexOf 与 arrayList 中的 customObject 一起使用

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:37:34 25 4
gpt4 key购买 nike

我希望能够使用 indexOf 方法返回对象的位置,但只想传递联系人的姓名来搜索它,有什么办法可以做到这一点吗?

我目前有这个方法:

private static ArrayList<Contacts> contactList = new ArrayList<Contacts>();

public class Contacts {
private String name;
private String number;


public Contacts(String name, String number) {
this.name = name;
this.number = number;
}

public String getName() {
return name;
}

public String getNumber() {
return number;
}

public void setName(String name) {
this.name = name;
}

public void setNumber(String number) {
this.number = number;
}



public int findItem(String name) {

return contactList.indexOf(name);
}

最佳答案

这是一个无需遍历整个列表即可实现此目的的函数,我认为复杂度低于 O(n):

public int findItem(String name)
{
int max = contactList.size();

//you might have to subtract this by one
//I'm not sure off the top
int descCnt = max;


for(int cnt = 0; cnt <= max/2; cnt++)
{
if(contactList.get(cnt).getName().equals(name)) return cnt;
if(contactList.get(descCnt).getName().equals(name)) return descCnt;
--descCnt;
}

}

关于java - 将 IndexOf 与 arrayList 中的 customObject 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39175557/

25 4 0