Здравствуйте, подскажите, пожалуйста, почему разное поведение со скобками и без?
return this.first == null ? 1 : 31 * this.first.hashCode() + this.last == null ? 1 : 25 * this.last.hashCode(); - получаю исключение при last = null;
return (this.first == null ? 1 : 31 * this.first.hashCode()) + (this.last == null ? 1 : 25 * this.last.hashCode()); - проходит без исключенияpackage com.javarush.task.task21.task2105;
import java.util.HashSet;
import java.util.Set;
/*
Исправить ошибку. Сравнение объектов
*/
public class Solution {
private final String first, last;
public Solution(String first, String last) {
this.first = first;
this.last = last;
}
@Override
public int hashCode() {
return (this.first == null ? 1 : 31 * this.first.hashCode()) + (this.last == null ? 1 : 25 * this.last.hashCode());
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Solution)) {
return false;
}
Solution n = (Solution) o;
return ((n.first!=null?n.first:"null").equals(this.first!=null?this.first:"null") && (n.last!=null?n.last:"null").equals(this.last!=null?this.last:"null"));
// return n.first.equals(first) && n.last.equals(last);
}
public static void main(String[] args) {
Set<Solution> s = new HashSet<>();
s.add(new Solution("null", null));
System.out.println(s.contains(new Solution("Micke", "Mouse")));
}
}