0

I want to compare database dump to xml and *.sql. In debagge toRemove and toAdd only differ in dimension. toRemove has size 3, toAdd has size 4. But after running the code, removeAll, toRemove has size 3 and toAdd has size 4. What's wrong?

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

Update:

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

1 回答 1

1

为了正确使用HashSet(以及HashMap,就此而言),您必须hashCode()按照以下合同实施 a :

  • 每当在 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;
}
于 2013-10-08T06:17:57.083 回答