我使用 Eclipse 自动工具为 person 对象实现 equals 方法。如果两个人反对,p1
并且p2
是null
,应该p1.equals(p2)
返回什么?当前实现提供了我的 Eclipse 返回True
。但是,我尝试与null
字符串对象进行比较,它抛出NullPointerException.
Here is the code。另外我想知道为什么不同运行的代码会给出不同的结果。我粘贴了下面的输出
class Parent2 {
private String name;
private int id;
public static int count = 0;
public Parent2(String name, int id) {
this.name = name;
this.id = id;
if (this.getClass() == Parent2.class)
count++;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Parent2 other = (Parent2) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null) {
System.out.println("here2");
return false;
}
} else if (!name.equals(other.name)) {
System.out.println("here");
return false;
}
return true;
}
}
public class App {
public static void main(String[] args) {
Parent2 par = new Parent2("aa", 5);
Parent2 par2 = new Parent2(null, 5);
Parent2 par3 = new Parent2(null, 5);
System.out.println(par.equals(par2));
System.out.println(par2.equals(par));
System.out.println(par3.equals(par2));
System.out.println("----------------------------------------");
String str = null;
String str2 = null;
System.out.println(str.equals(str2));
System.out.println(str + "; " + str2);
}
}
每次执行的输出都不同,这里有一些:
here
false
here2Exception in thread "main" java.lang.NullPointerException
at RoundTwo.App.main(App.java:64)
false
true
----------------------------------------
输出2:
here
Exception in thread "main" java.lang.NullPointerException
at RoundTwo.App.main(App.java:64)
false
here2
false
true
----------------------------------------
输出3:
here
false
here2
false
true
Exception in thread "main" java.lang.NullPointerException
at RoundTwo.App.main(App.java:64)
----------------------------------------
输出4:
here
falseException in thread "main" java.lang.NullPointerException
at RoundTwo.App.main(App.java:64)
here2
false
true
----------------------------------------
输出5:
here
false
here2
false
true
----------------------------------------
Exception in thread "main" java.lang.NullPointerException
at RoundTwo.App.main(App.java:64)
只有最后一个输出,执行string equals
抛出的代码部分NullpointerException
感谢您的帮助