2

I have 2 linked lists.

I have the same object in both of those lists. By same object, I mean the object has the same state, but is referenced by a different object pointer.

I can call .remove(object); from the first list to remove it, but if I do the same for the second list it is not removed (because the object pointer reference is different)

Is there an easy way to remove objects with the same state from various lists?

Thinking about it, I will probably loop through the second list comparing state on its objects, but I was looking for a cleaner way

Jimmy
  • 16,123
  • 39
  • 133
  • 213

3 Answers3

3

Override the equals method for the object. If they have similar equivalence functionality they should be removed correctly from both lists.

Edit - for the sake of correctnes:

You should always override the hashCode method when overriding the equals method. Failure to do so may not show any strange functionality in your List but once you try to use the same object in say a HashMap, you may find that the remove or put may not function like you wanted.

John Vint
  • 39,695
  • 7
  • 78
  • 108
0

If the objects have the same state, then it is probably correct for you to override their equals and hashCode methods to reflect this. If the objects are the same as far as the equals method is concerned, then you can call remove on both lists.

If the linked lists are implemented properly, the fact that different objects are being pointed to in memory should not prevent this from working. According to the List API, the remove method:

...removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists)...

Michael McGowan
  • 6,528
  • 8
  • 42
  • 70
0

You must override both equals() and hashCode() on you object. When these are not overriden the default behaviour is to compare object identity ie the reference. When you override Equals you can change the comparison to be based on the object state, ie logically equality. It is important to remember to override hashCode as well, as if this is not done it can lead to strange behaviour when you object is used in a HashSet or HashTable.

mR_fr0g
  • 8,462
  • 7
  • 39
  • 54