Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java collection of unique elements

Tags:

java

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.

like image 503
jbenz Avatar asked Apr 15 '13 06:04

jbenz


1 Answers

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.

like image 150
Android Killer Avatar answered Oct 23 '22 23:10

Android Killer