<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(Solution n) {
if (this == n){
return true;
}
if ( n instanceof Solution){
return true;
}
return n.first!=null && n.last!=null && this.first.equals(n.first)&& this.last.equals(n.last);
}
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (last != null ? last.hashCode() : 0);
return result;
}
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")));
}
}
>
package com.javarush.task.task21.task2104;
public class Drob {
private int up;
private int down;
public Drob(int up, int down) {
this.up = up;
this.down = down;
}
public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj.getClass() != this.getClass())
return false;
Drob other = (Drob) obj;
return this.up * other.down == this.down * other.up;
}
public static void main(String[] args) {
Drob first = new Drob(6, 10);
Drob seconds = new Drob(12, 20);
System.out.println(first.equals(seconds));
}
}