10

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.

jbenz
  • 101
  • 1
  • 1
  • 3

4 Answers4

11

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.

Community
  • 1
  • 1
Android Killer
  • 18,174
  • 13
  • 67
  • 90
  • You need working hashCode and equals for that (at least the latter is not the case here). – Thilo Apr 15 '13 at 06:41
  • 1
    Unique based on what ? That's the question. Can I provide a way to tell whether two elements are unique when I instantiate the hashset ? – jbenz Apr 15 '13 at 06:43
  • Does not help to just override hashCode. You also need equals (which OP does not want to use) – Thilo Apr 15 '13 at 06:46
  • Not okay, because not using equals is the whole point of the question (which of course is a bad idea in the first place). – Thilo Apr 15 '13 at 06:48
  • @Thilo i edited to use equals method with a link between hashcode and equals method ? didn't u read that ? – Android Killer Apr 15 '13 at 06:51
  • But OP does not want to use equals. – Thilo Apr 15 '13 at 06:59
2

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

2

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.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • Could I maybe use my own collection, inherited from set, where I override the method in charge of the equality test ? – jbenz Apr 15 '13 at 06:45
0

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);

Legna
  • 1,632
  • 15
  • 15