簡體   English   中英

從接口集中移除全部

[英]removeAll from Interface Set

我想比較數據庫轉儲到xml和* .sql。 在解toRemovetoRemovetoAdd僅在尺寸上有所不同。 toRemove大小為3, toAdd大小為4。但是在運行代碼后, removeAlltoRemove大小為3和toAdd大小為4。這是怎么回事?

final DBHashSet fromdb = new DBHashSet(strURL, strUser, strPassword);
final DBHashSet fromxml = new DBHashSet(namefile);

Set<DBRecord> toRemove = new HashSet<DBRecord>(fromdb);
toRemove.removeAll(fromxml);

Set<DBRecord> toAdd = new HashSet<DBRecord>(fromxml);
toAdd.removeAll(fromdb);

更新:

public class DBRecord {
    public String depcode;
    public String depjob;
    public String description;

    public DBRecord(String newdepcode, String newdepjobe, String newdesc) {
        this.depcode = newdepcode;
        this.depjob = newdepjobe;
        this.description = newdesc;
    }

    public String getKey() {
        return depcode + depjob;
    }

    public boolean IsEqualsKey(DBRecord rec) {
        return (this.getKey().equals(rec.getKey()));
    }

    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (o == null)
            return false;
        if (!(getClass() == o.getClass()))
            return false;
        else {
            DBRecord rec = (DBRecord) o;
            if ((rec.depcode.equals(this.depcode)) && (rec.depjob.equals(this.depjob)))
                return true;
            else
                return false;
        }
    }
}

為了正確使用HashSet (和HashMap ),必須按照以下約定實現hashCode()

  • 在Java應用程序的執行過程中,只要在同一對象上多次調用它,則hashCode方法必須一致地返回相同的整數,前提是未修改該對象的equals比較中使用的信息。 從一個應用程序的執行到同一應用程序的另一執行,此整數不必保持一致。
  • 如果根據equals(Object)方法,兩個對象相等,則在兩個對象中的每個對象上調用hashCode方法必須產生相同的整數結果。
  • 根據equals(java.lang.Object)方法,如果兩個對象不相等,則不需要在兩個對象中的每個對象上調用hashCode方法必須產生不同的整數結果。 但是,程序員應該意識到,為不相等的對象生成不同的整數結果可能會提高哈希表的性能。

您為DBRecord提供的代碼不會覆蓋它,因此是問題所在。 您可能希望通過以下方式或類似方式覆蓋它:

@Override
public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + depcode.hashCode();
  result = prime * result + depjob.hashCode());
  return result;
}

暫無
暫無

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

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