【问题标题】:check if a list already contains an object with similar values - java检查列表是否已经包含具有相似值的对象 - java
【发布时间】:2016-03-24 19:24:47
【问题描述】:

仅当给定列表尚未包含具有相似属性的对象时,我才需要将对象添加到列表中

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);  
}

我尝试contains() 检查现有列表。如果列表已经有一个对象,比如 jj.type = "TypeA"j.id = "A",我不想将它添加到列表中。

您能否通过覆盖等于或任何可以做到的解决方案来帮助我实现这一目标?

【问题讨论】:

  • 不幸的是我不能使用集合,那些类已经写在现有系统中。如果我可以根据现有标准提出条件,那就太好了。

标签: java arraylist collections


【解决方案1】:

在您的 Identifier 类中实现 equals()hashCode()

如果您不想在添加元素之前执行检查,可以将您的 listObjectList 更改为 SetSet 是一个不包含重复元素的集合。

以下是 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;
}

【讨论】:

  • 并用你的IDE生成equalshashCode,不用写了+1
  • 这不会导致这里出现一些错误,因为Identifier 是可变对象吗?
  • 是的,你可以使用 List 并在添加元素之前执行检查。
  • @hbelmiro,这是实现equals 的肮脏方式,如果我们有两个以上的字段,你会怎么做?
  • @AndrewTobilko 我只想添加其他字段。你有什么建议?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-02
  • 2022-08-18
  • 2019-07-04
  • 2021-09-18
相关资源
最近更新 更多