2015-09-07 11:44:36 -06:00
|
|
|
// typeinfo/pets/Individual.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
package typeinfo.pets;
|
2017-01-08 22:55:49 -08:00
|
|
|
import java.util.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
2016-01-25 18:05:55 -08:00
|
|
|
public class
|
|
|
|
Individual implements Comparable<Individual> {
|
2015-06-15 17:47:35 -07:00
|
|
|
private static long counter = 0;
|
|
|
|
private final long id = counter++;
|
|
|
|
private String name;
|
|
|
|
public Individual(String name) { this.name = name; }
|
|
|
|
// 'name' is optional:
|
|
|
|
public Individual() {}
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public String toString() {
|
2015-06-15 17:47:35 -07:00
|
|
|
return getClass().getSimpleName() +
|
|
|
|
(name == null ? "" : " " + name);
|
|
|
|
}
|
|
|
|
public long id() { return id; }
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public boolean equals(Object o) {
|
2015-06-15 17:47:35 -07:00
|
|
|
return o instanceof Individual &&
|
2017-01-08 22:55:49 -08:00
|
|
|
Objects.equals(id, ((Individual)o).id);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public int hashCode() {
|
2017-01-10 14:11:16 -08:00
|
|
|
return Objects.hash(name, id);
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public int compareTo(Individual arg) {
|
2015-06-15 17:47:35 -07:00
|
|
|
// Compare by class name first:
|
|
|
|
String first = getClass().getSimpleName();
|
|
|
|
String argFirst = arg.getClass().getSimpleName();
|
|
|
|
int firstCompare = first.compareTo(argFirst);
|
|
|
|
if(firstCompare != 0)
|
2017-01-10 14:11:16 -08:00
|
|
|
return firstCompare;
|
2015-06-15 17:47:35 -07:00
|
|
|
if(name != null && arg.name != null) {
|
|
|
|
int secondCompare = name.compareTo(arg.name);
|
|
|
|
if(secondCompare != 0)
|
|
|
|
return secondCompare;
|
|
|
|
}
|
|
|
|
return (arg.id < id ? -1 : (arg.id == id ? 0 : 1));
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|