Dan*_*Dan 17 java eclipse equals
我对java很新,我只是想了解@Override一下这些equals()和hashcode()方法.
我知道equals方法要正确,它需要:
a.equals(a)a.equals(b) 然后 b.equals(a)a.equals(b) && b.equals(c) 然后 a.equals(c) ! a.equals(null)我在努力确定上述属性中的哪一个并且在编写equals方法的上面时并不满意.
我知道eclipse可以为我生成这些,但是因为我还没有完全理解这个概念,所以写出来可以帮助我学习.
我已经写出了我认为正确的方法,但是当我查看eclipse生成的版本时,我似乎"缺少"某些方面.
例:
public class People {
private Name first; //Invariants --> !Null, !=last
private Name last; // !Null, !=first
private int age; // !Null, ! <=0
...
}
Run Code Online (Sandbox Code Playgroud)
我写的:
public boolean equals(Object obj){
if (obj == null){
return false;
}
if (!(obj instanceof People)){
return false;
}
People other = (People) obj;
if (this.age != other.age){
return false;
}
if (! this.first.equals(other.first)){
return false;
}
if (! this.last.equals(other.last)){
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
vs eclipse生成
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
People other = (People) obj;
if (first == null) {
if (other.first != null)
return false;
} else if (!first.equals(other.first))
return false;
if (age != other.age)
return false;
if (last == null) {
if (other.last != null)
return false;
} else if (!last.equals(other.last))
return false;
return true;
}
Run Code Online (Sandbox Code Playgroud)
我失踪了:
if (this == obj)
return true;
Run Code Online (Sandbox Code Playgroud)if (getClass() != obj.getClass())
return false;
Run Code Online (Sandbox Code Playgroud)并为每个变量:
if (first == null) {
if (other.first != null)
return false;
} else if (!first.equals(other.first))
return false;
Run Code Online (Sandbox Code Playgroud)我不确定是什么getClass(),我的实施是不正确的?
第一段代码:
if (this == obj)
return true;
Run Code Online (Sandbox Code Playgroud)
这可以在您将对象引用与自身进行比较时提高性能.示例:a.equals(a);.
第二段代码:
if (getClass() != obj.getClass())
return false;
Run Code Online (Sandbox Code Playgroud)
这比较了被比较的引用的类是否是相同的类this.使用这种方法的区别在于instanceof它与子类进行比较时更具限制性.例:
public class Foo { }
public class Bar extends Foo { }
//...
Foo foo = new Bar();
System.out.println(foo instanceof Bar); //prints true
System.out.println(foo instanceof Foo); //prints true
Foo foo2 = new Foo();
System.out.println(foo.getClass() == foo2.getClass()); //prints false
Run Code Online (Sandbox Code Playgroud)
你应该选择哪一个?没有好的或坏的方法,这将取决于您所需的设计.
第三段代码:
if (first == null) {
if (other.first != null)
return false;
} else if (!first.equals(other.first))
return false; //For each variable.
Run Code Online (Sandbox Code Playgroud)
这只是对类中每个对象引用字段的空检查.请注意,如果this.first是,null那么this.first.equals(...)将抛出一个NullPointerException.
| 归档时间: |
|
| 查看次数: |
769 次 |
| 最近记录: |