Reputation: 9374
I wonder if there is a nice way to have Set on objects, but constrained on custom fields.
For example I need a Set
of POJO's:
class MyPojo {
private String name;
private Map<Object, Object> stuff;
//getters, setters, constructor
}
And I want to have a Set
where they will be unique by name.
I could implement hash
and equals
based on name
property, but then I can't use really equals
to compare them.
Is there some nice workaround or maybe Guava/apache commons collection for this?
Upvotes: 2
Views: 67
Reputation: 599
You can create wrapper objects. It's like a decorator pattern. You wrap your original object with different hash implementations and then wrapped object will be used in the Set.
Upvotes: 4
Reputation: 393966
You can use a HashMap<String,MyPojo>
instead of a Set<MyPojo>
. This way, each name
can appear at most once in the Map
.
Upvotes: 2