在 Java 中使用 equals() 方法时如何避免空异常
How to avoid null exception when using equals() method in Java
我试图比较两个不同对象的名称,但在使用 equals()
方法将项目与 null 进行比较时,我一直遇到异常。我尝试了很多方法,包括other.equals(哈哈)、haha.equals(其他)等等,但都失败了。
public final class ItemImpl implements Item {
private final String name;
public ItemImpl(String name) {
if (name == null) {
throw new IllegalArgumentException("name cannot be null!");
}
this.name = name;
}
@Override
public String getName() {
return this.name;
}
public boolean equals(Object other) {
Object haha = name;
return other.toString().equals(haha.toString());
}
public String toString() {
return this.name;
}
}
调用 Objects.equals
容忍空值。
Objects.equals(a,b);
为您完成这项工作,在您的情况下,您还必须查看您调用的 toString 方法不在空引用上。
所以使用:
return other != null && Objects.equals(toString(), other.toString());
我试图比较两个不同对象的名称,但在使用 equals()
方法将项目与 null 进行比较时,我一直遇到异常。我尝试了很多方法,包括other.equals(哈哈)、haha.equals(其他)等等,但都失败了。
public final class ItemImpl implements Item {
private final String name;
public ItemImpl(String name) {
if (name == null) {
throw new IllegalArgumentException("name cannot be null!");
}
this.name = name;
}
@Override
public String getName() {
return this.name;
}
public boolean equals(Object other) {
Object haha = name;
return other.toString().equals(haha.toString());
}
public String toString() {
return this.name;
}
}
调用 Objects.equals
容忍空值。
Objects.equals(a,b);
为您完成这项工作,在您的情况下,您还必须查看您调用的 toString 方法不在空引用上。
所以使用:
return other != null && Objects.equals(toString(), other.toString());