当我必须编写近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);
}
}
Run Code Online (Sandbox Code Playgroud)
Tom*_*Tom 12
Google的guava库具有处理nullness 的Objects
类Objects#equal
.它确实有助于缩小规模.用你的例子,我会写:
@Override public boolean equals(Object other) {
if (!(other instanceof Id)) {
return false;
}
Id o = (Id) other;
return Objects.equal(this.name, o.name);
}
Run Code Online (Sandbox Code Playgroud)
文档在这里.
还要注意的是有Objects#hashCode
和Objects#toStringHelper
帮助hashCode
,并toString
为好!
另请参阅Effective Java 2nd Edition了解如何编写equals()
.
卢声远*_* Lu 10
如果您使用Eclipse,请单击" Source " - >" generate hashCode()和equals() ".有很多选项可以自动创建equals().
有些图书馆会为你做这件事.例如,commons-lang有EqualsBuilder
此外,这两行似乎做同样的事情:
if (o == null)
return false;
if (null == (Id) o)
return false;
Run Code Online (Sandbox Code Playgroud)
也许你这意味着:
if (o == null)
return false;
if (this == o)
return true;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4417 次 |
最近记录: |