I have tested the code changing the value of the properties to null, etc. And it gives me the correct result.
Any hint?
Thanks
package com.codegym.task.task21.task2105;
import java.util.HashSet;
import java.util.Set;
/*
Fix the bug. Comparing objects
*/
public class Solution {
private final String first, last;
public Solution(String first, String last) {
this.first = first;
this.last = last;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Solution))
return false;
if (o == null) return false;
if (this == o) return true;
// both first == null
if (this.first == null && ((Solution) o).first == null) {
// both last == null
if (this.last == null && ((Solution) o).last == null) return true;
// both last != null && last == last
if (this.last != null && ((Solution) o).last != null) {
return this.last.equals(((Solution) o).last);
}
}
// both last == null
if (this.last == null && ((Solution) o).last == null) {
// both first != null && first == first
if (this.first != null && ((Solution) o).first != null) {
return this.first.equals(((Solution) o).first);
}
}
return this.first.equals(((Solution) o).first) && this.last.equals(((Solution) o).last);
}
@Override
public int hashCode() {
if (this.first == null || this.last == null) return 0;
return first.hashCode() + last.hashCode() * 44;
}
public static void main(String[] args) {
Set<Solution> s = new HashSet<>();
s.add(new Solution("Mickey", "Mouse"));
System.out.println(s.contains(new Solution("Mickey", "Mouse")));
}
}