java检查对象列表是否包含具有具体名称的对象

标签 java list object equals hashcode

我有对象列表:

List<City> cities = city.getList();

我想删除重复项(重复项是指具有相同参数值 name 和不同(id 和其他参数)的对象);

我有代码:

for(City c: cities) {
    System.out.println("analise " + c.name);
    if(!temp.contains(c)) {
        temp.add(c);
    }
}

我已经为 hashCode() 和 equals() 方法编写了:

@Override
public int hashCode() {
    return id.hashCode();
}

...

  @Override
    public boolean equals(Object other) {
        if (other == null) return false;
        if (other == this) return true;
        if (!(other instanceof GenericDictionary))return false;
        GenericDictionary otherMyClass = (GenericDictionary) other;
        if(this.name == otherMyClass.name) {
            return true;
        } else {
            return false;
        }
    }

但它不适用。它使用 object.equals() 方法而不是我的

最佳答案

看起来您的问题出在字符串比较中:

if(this.name == otherMyClass.name)

将其更改为:

if(this.name.equals(otherMyClass.name))

关于java检查对象列表是否包含具有具体名称的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26969236/

相关文章:

c# - 为什么列表中有一个数组? C#

python - 如果不同数据帧的项目相等但尊重 Pandas 的条件,则打印值

PHP:对象的array_filter?

java - Spring 启动 : BeanFactoryPostProcessor's postProcessBeanFactory not getting called

java - 如何在 Windows 中设置 ESC/Java2 环境并使用 ESC/Java2 构建/运行?

java - "Quick and Dirty"Java中的人脸识别和数据库存储/查找

java - 将字节数组存储在对象中,然后将其转换为 ObjectOutputStream? (卡住)

python - 从字符列表中删除方括号

python - 'self' 关键字在类方法中是强制性的吗?

Javascript 数组作为更具可读性的数组