I'm looking for a suggestion.
I have a Person
class with String firstName and String lastName
When i'm tying to insert the list values with the same String like :
set.add(new Person("firstName","lastName"))
set.add(new Person("firstName","lastName"))
The set doesn`t filter the objects and they still getting in the set. There is any suggestion to create set list without overriding the equales and hashcode functions? Maybe with guava or some groovy list? Thanks, Or.
You can create a TreeSet with your own Comparator.
In Guava there's an Equivalence class designed to such things. Create your own
Equivalence
class like this one:And then this code
prints
Of course it's a bit verbose, but you can create ForwardingSet to automatically wrap and unwrap
Person
s for you.You can't, without violating the contract of
Set
. Either don't use aSet
, or wrap thePerson
in another class that implementsequals
andhashcode
based on the innerPerson
(see the other answer for a way to do this in Guava).Here's a rough attempt at my map suggestion.