Write your own type of comparable
The comparable interface is composed of a single method:
public interface Comparable {
public int compareTo(Object o);
}
The CompareTo method compares the receiving object with a specific object and returns a negative integer, an empty, or a positive integer, respectively, when the receiving object is less than, equal to, or greater than a particular object. If a particular object cannot be compared to the receiving object, the method throws a classcastexception. This is a class that represents someone's name (a class representing a person "s name) that implements the comparable:
import java.util.*;
public class Name implements comparable {
Private String firstName, LastName;
Public Name (String firstName, String lastName) {
if (Firstname==null | | lastname==null)
throw new Nullpointer Exception ();
This.firstname = firstName;
This.lastname = lastName;
}
Public String firstName () {return firstName;}
Public String LastName () {return lastName;}
Public boolean equals (Object o) {
if (! o instanceof Name)
return false;
Name n = (name) o;
return N.firstname.equals (firstName) &&
N.lastname.equals (lastName);
}
Public int hashcode () {
return 31*firstname.hashcode () + Lastname.hashcode ();
}
Public String toString () {return firstName + "" + LastName;}
Public int compareTo (Object o) {
Name n = (Name) o;
int lastcmp = Lastname.compareto (n.lastname);
RET Urn (lastcmp!=0 lastcmp:
Firstname.compareto (N.firstname));
}
To make this example shorter, the class is constrained by the fact that it does not support the middle name and that it requires both a-name and last name, which is not universally universal. Nevertheless, this example still has several important points:
The Name object is invariant (immutable). All other things that are equal and immutable types are the problems of how to do this, especially for objects that will be used as elements in Sets or as keys in Maps. If you make changes to the elements or keys in these objects, the set of objects will be interrupted.