Но не проходит.. и прочитал комменты.
Вопрос - почему не проходит? и еще вопрос:
в переопределенном методе equals мы проверяем объект на принадлежность Solution через instanceof.
Обязательно ли в таком случает приводить через Solution solution = (Solution) o? Ведь мы и так уже проверили что он Solution и если нет - вернули false.
package com.javarush.task.task21.task2104;
import java.util.HashSet;
import java.util.Objects;
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;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || o.getClass() != this.getClass()) return false;
if (!(o instanceof Solution))
return false;
Solution solution = (Solution) o;
//boolean result = false;
/*if (this.first != null && this.first.equals(solution.first)) {
result = true;
}*/
boolean f = this.first != null && this.first.equals(solution.first);
/*if (this.last != null && this.last.equals(solution.last)) {
result = true;
}*/
boolean l = this.last != null && this.last.equals(solution.last);
return f && l;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = first != null ? first.hashCode() : 1;
result = prime * result + (last != null ? last.hashCode() : 1);
return result;
}
public static void main(String[] args) {
Set<Solution> s = new HashSet<>();
s.add(new Solution("Donald", "Duck"));
//s.add(new Solution("Donald", "Duck"));
for (Solution t : s) {
//System.out.println(t.first.hashCode() + " " + t.last.hashCode() + " " + t.hashCode());
}
System.out.println(s.contains(new Solution("Donald", "Duck")));
}
}