Here is the answer of this question but I need is there any other way
假设Person是一个包含属性的类
- 人员编号
- 人名
- 个人地址
一个 ArrayList 包含 thousand person 对象,我想检查“11”personId 是否在 ArayList 中?
一种方法是迭代(循环)arraylist 并逐个检查。
还有其他方法可以解决吗?
最佳答案
在您的 POJO 中覆盖 equals() 和 hashcode() 方法以获取 person 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
}
}
关于java - 如何检查对象 ArrayList 是否包含没有循环的对象的单个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28498326/