Java: howto write equals() short

2022-09-05 00:39:38

当我不得不写近10行代码说.您可以轻松地看到,在这种书写方式中,行数会随着属性数的增加而急剧增加。2 Objects are equal, when their type is equal and both's attribute is equal

public class Id implements Node {

        private String name;

        public Id(String name) {
                this.name = name;
        }

        public boolean equals(Object o) {
                if (o == null)
                        return false;
                if (null == (Id) o)
                        return false;
                Id i = (Id) o;
                if ((this.name != null && i.name == null) || (this.name == null && i.name != null))
                        return false;
                return (this.name == null && i.name == null) || this.name.equals(i.name);
        }

}

答案 1

谷歌的番石榴库有处理空性的类。它确实有助于使事情变得更小。以你的例子,我会写:ObjectsObjects#equal

@Override public boolean equals(Object other) {
  if (!(other instanceof Id)) {
    return false;
  }
  Id o = (Id) other;
  return Objects.equal(this.name, o.name);
}

文档在这里

还要注意的是,有和帮助,以及!Objects#hashCodeObjects#toStringHelperhashCodetoString

另请参阅 Effective Java 2nd Edition,了解如何编写 equals()。


答案 2

如果您使用 Eclipse,请单击“Source” ->“生成 hashCode() and equals()”。有许多选项可以自动创建 equals()。


推荐