Доброго дня. подозреваю что дело в hasCode я его слабо понял этот метод. Подскажите где проблема пожалуйста.
Так же прошу разъяснить почему в прошлых примерах было 31*name.hashCode зачем мы hashCode умножаем на 31???
package com.javarush.task.task21.task2104;
import java.util.HashSet;
import java.util.Set;
/*
Equals and HashCode
*/
public class Solution {
private final String first, last;
public Solution(String first, String last) {
this.first = first;
this.last = last;
}
@Override
public int hashCode() {
int result;
if (first == null && last !=null) result = 31*last.hashCode();
else if (first != null && last ==null) result = 31*first.hashCode();
else result = first.hashCode() + last.hashCode();
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof Solution)) return false;
Solution sol = (Solution) o;
if (first != null ? !first.equals(sol.first):sol.first != null) return false;
return (last != null ? last.equals(sol.last):sol.last == null);
}
public static void main(String[] args) {
Set<Solution> s = new HashSet<>();
s.add(new Solution("Donald", "Duck"));
System.out.println(s.contains(new Solution("Donald", "Duck")));
}
}