jbenz
jbenz

Reputation: 101

java collection of unique elements

I have a Collection coll of myObject. I'd like to add an element to coll only if there is no such element in the collection.

I have overriden the equals method of myObject. It checks for the equality of its 20 attributes.

However in the case of the collection, I'd like to make the equality check (and hence the add) based only on one of these attributes.

Maybe my architecture is flawed, and I shouldn't have two definitions of equals, and should instead have 2 different objects.

However, is it possible, without too much refactoring, to achieve what I want from here ? That is to say, I'd like some sort of a Set collection, where I could tell how to make the comparison check. This would be similar to the Collection.sort() method, where you can provide the comparator to check for the comparison.

Upvotes: 10

Views: 39818

Answers (4)

Legna
Legna

Reputation: 1681

By using a TreeSet(Comparator comparator) you don't need to rely on the 'equals/hashCode' implementation.

Similarly if your collection is a list you can sort it using a comparator Collections.sort(List list, Comparator c);

Upvotes: 0

Thilo
Thilo

Reputation: 262852

You cannot use the existing containers to enforce uniqueness here, because they all want to use equals.

If it is only one attribute, you could use a Map, with that attribute as a key. That will allow only one entry per value for that attribute.

equals and hashCode are intended to be used with Collections. You should change your design. Maybe call your own equals (the one you have now) something else. Maybe don't put these things into collections directly, but wrapped into an adapter of some sort.

Upvotes: 2

Android Killer
Android Killer

Reputation: 18509

go for HashSet.It will store unique values.As from comments here, you have to override the hashcode and equals methods to provide uniqueness of every object.You can read relation between these two methods here.

Upvotes: 11

user1907906
user1907906

Reputation:

You are looking for a Set and one of its implementations.

Upvotes: 2

Related Questions