发现如果对象的列表包含指定的字段值的东西吗? [英] Finding out if a list of Objects contains something with a specified field value?
问题描述
我有来自DB接收DTO的列表,他们有一个ID。我想确保我的列表中包含有指定ID的对象。显然,在这种情况下,预期的领域创建一个对象将不会帮助,因为包括()调用是Object.equals(),他们不会是平等的。
I have a list of DTO received from a DB, and they have an ID. I want to ensure that my list contains an object with a specified ID. Apparently creating an object with expected fields in this case won't help because contains() calls for Object.equals(), and they won't be equal.
我走过来,像这样的解决方案:创建一个接口 HasId
,实现了它在我所有的DTO,并继承ArrayList的使用具有<$ C $一个新的类C>包含(长ID)方法。
I came up to a solution like so: created an interface HasId
, implemented it in all my DTOs, and inherited ArrayList with a new class that has contains(Long id)
method.
public interface HasId {
void setId(Long id);
Long getId();
}
public class SearchableList<T extends HasId> extends ArrayList<T> {
public boolean contains(Long id) {
for (T o : this) {
if (o.getId() == id)
return true;
}
return false;
}
}
但在这种情况下,我不能强制转换列表和ArrayList到SearchableList ...
我住在一起,但希望确保我没有发明了自行车。
But in this case I can't typecast List and ArrayList to SearchableList... I'd live with that, but wanted to make sure that I'm not inventing the bicycle.
推荐答案
我建议创建简单的静态方法,像你这样写的,没有任何额外的接口:
I propose to create simple static method like you wrote, without any additional interfaces:
public static boolean containsId(List<DTO> list, long id) {
for (DTO object : list) {
if (object.getId() == id) {
return true;
}
}
return false;
}
这篇关于发现如果对象的列表包含指定的字段值的东西吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!