Collection of unique java elements.

I have a collection of coll myObject. I would like to add an element to coll only if the collection does not have such an element.

I redefined the equals method myObject. He checks the equality of his 20 attributes.

However, in the case of a collection, I would like to do an equality check (and therefore add) based on only one of these attributes.

Maybe my architecture is wrong, and I should not have two equals definitions, and instead you should have two different objects.

However, is it possible, not too much refactoring, to achieve what I want from here? That is, I need some kind of Set collection, where I could tell how to do a comparison check. This will be similar to the Collection.sort () method, where you can give the comparator the ability to check the comparison.

+8
java
source share
4 answers

Go to HashSet . It will store unique values. As from the comments here, you must override the hashcode and equals methods to ensure that each object is unique. You can read the relationship between the two methods here .

+8
source share

You are looking for Set and one of its implementations.

+2
source share

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

If this is only one attribute, you can use Map, with this attribute as a key. This will allow you to use only one item for each attribute.

equals and hashCode are for use with collections. You have to change your design. Maybe call your own peers (the one you have now), something else. Perhaps do not put these things in the collection directly, but are wrapped in some kind of adapter.

+2
source share

Using a TreeSet (comparator comparator), you do not need to rely on the implementation of 'equals / hashCode'.

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

0
source share

All Articles