I have an unusual requirement to implement.
I need to store several objects in a Set.
Let's use this simple class as an example -
class Name {
String first;
String last;
String middle;
}
My business rule is that two Name objects are considered equal if the first, last, and middle fields are all equal OR if first and last fields are equal and one (or both) of the objects has null for the middle field.
So in implementing the hash and equals methods for my Name class I could have a use cases where equals returns true for the two objects but the hash for the two objects returns a different value (because one object has a value for middle and the other object has null for middle).
The actual Set implementation I use cannot be HashSet because HashSet uses the hash method to determine whether or not to add the object to the Set. In my example the hash method will return a different value for these two objects name1 (first=Bruce, last=Phillips, middle=Allen) and name2 (first=Bruce, last=Phillips, middle=null) even though my equals method will return true for the two objects.
My plan is to use TreeSet and have my Name class implement comparable. I don't really care about the order of Name class objects in my TreeSet but by using TreeSet and implementing comparable's compareTo method I can use the equals method in class Name (which checks if one of the objects has null for middle field) to determine if the two object's are equal.
Any drawbacks to this approach to solving my requirement?
Thank you for the help.
Bruce