如何检查对象 ArrayList 是否包含没有循环的对象的单个属性

How to check Object ArrayList contain single attribute of Object without Loop

Here is the answer of this question but I need is there any other way

假设人是一个class包含属性

一个 ArrayList 包含千人对象,我想检查“11”personId 是否在 ArayList 中?

一种方法是迭代(循环)arraylist 并逐个检查。

还有其他方法可以解决吗?

persionId的基础上实施equalshashCodejava.util.ArrayList#contains 会给你结果。这个解决方案与遍历列表并找到对象一样好。

在您的 POJO 中覆盖 equals() 和 hashcode() 方法以获得人员 ID

例如:

import java.util.ArrayList;

public class Test {
private int personId;
private String name;
//getters and Setters



@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + personId;
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
       return true;
    if (obj == null)
       return false;
    if (getClass() != obj.getClass())
       return false;
    Test other = (Test) obj;
    if (personId != other.personId)
       return false;
    return true;
}
public static void main(String[] args) {
    ArrayList<Test> test=new ArrayList<Test>();

Test t=new Test();
t.setName("Sireesh");
t.setPersonId(1);

Test t1=new Test();
t1.setName("Ramesh");
t1.setPersonId(2);

Test t2=new Test();
t2.setName("Rajesh");
t2.setPersonId(3);


test.add(t);
test.add(t1);
test.add(t2);

Test tx=new Test();
tx.setPersonId(1);
System.out.println(test.contains(tx));
//Returns true

}
}