2017-01-10 14:11:16 -08:00
|
|
|
// equalshashcode/SubtypeEquality.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2017-01-10 14:11:16 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
|
|
// Visit http://OnJava8.com for more book information.
|
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
enum Size { SMALL, MEDIUM, LARGE }
|
|
|
|
|
|
|
|
class Animal {
|
|
|
|
private static int counter = 0;
|
|
|
|
private final int id = counter++;
|
|
|
|
private final String name;
|
|
|
|
private final Size size;
|
2017-05-01 14:33:10 -06:00
|
|
|
Animal(String name, Size size) {
|
2017-01-10 14:11:16 -08:00
|
|
|
this.name = name;
|
|
|
|
this.size = size;
|
|
|
|
}
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public boolean equals(Object rval) {
|
2017-01-10 14:11:16 -08:00
|
|
|
return rval instanceof Animal &&
|
|
|
|
// Objects.equals(id, ((Animal)rval).id) && // [1]
|
|
|
|
Objects.equals(name, ((Animal)rval).name) &&
|
|
|
|
Objects.equals(size, ((Animal)rval).size);
|
|
|
|
}
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public int hashCode() {
|
2017-01-10 14:11:16 -08:00
|
|
|
return Objects.hash(name, size);
|
2021-01-31 15:42:31 -07:00
|
|
|
// return Objects.hash(name, size, id); // [2]
|
2017-01-10 14:11:16 -08:00
|
|
|
}
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public String toString() {
|
2017-01-10 14:11:16 -08:00
|
|
|
return String.format("%s[%d]: %s %s %x",
|
|
|
|
getClass().getSimpleName(), id,
|
|
|
|
name, size, hashCode());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Dog extends Animal {
|
2017-05-01 14:33:10 -06:00
|
|
|
Dog(String name, Size size) {
|
2017-01-10 14:11:16 -08:00
|
|
|
super(name, size);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class Pig extends Animal {
|
2017-05-01 14:33:10 -06:00
|
|
|
Pig(String name, Size size) {
|
2017-01-10 14:11:16 -08:00
|
|
|
super(name, size);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class SubtypeEquality {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
Set<Animal> pets = new HashSet<>();
|
|
|
|
pets.add(new Dog("Ralph", Size.MEDIUM));
|
|
|
|
pets.add(new Pig("Ralph", Size.MEDIUM));
|
|
|
|
pets.forEach(System.out::println);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
/* Output:
|
2021-01-31 15:42:31 -07:00
|
|
|
Dog[0]: Ralph MEDIUM 931523a9
|
2017-01-10 14:11:16 -08:00
|
|
|
*/
|