Rk *_*iri 2 java collections arraylist
仅当给定列表尚未包含具有类似属性的对象时,我才需要将对象添加到列表中
List<Identifier> listObject; //list
Identifier i = new Identifier(); //New object to be added
i.type = "TypeA";
i.id = "A";
if(!listObject.contains(i)) { // check
listObject.add(i);
}
Run Code Online (Sandbox Code Playgroud)
我试图contains()检查现有列表.如果列表中已经有一个对象说j有j.type = "TypeA"和j.id = "A",我不想给添加到列表中.
你可以通过覆盖平等或任何可以解决的解决方案来帮助我实现这一目标吗?
实施equals()并hashCode()在您的Identifier课堂上.
如果您不想在添加元素之前执行检查,则可以将listObjectfrom 更改List为Set.A Set是不包含重复元素的集合.
下面是Eclipse IDE自动创建的实现示例:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Identifier other = (Identifier) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
881 次 |
| 最近记录: |