簡體   English   中英

java檢查對象列表是否包含具體名稱的對象

[英]java check if list of object contains object with concrete name

我有對象列表:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM