1

I currently have a List of Objects. Removal of an object is done via:

if (mProducts.contains(orderProduct)) {
   mProducts.remove(orderProduct);
   .
   . 

However the javadocs for List states

Removes the first occurrence of the specified object from this {@code List}.

I need to remove the given object from the list and NOT just the first object. What is the correct approach here? Can I provide my own implementation of List.remove or use an alternative data structure?

Thanks, Otterman

Otterman
  • 530
  • 2
  • 5
  • 16
  • 2
    "_first occurrence of the **specified object**_" If you specify a particular object and it finds 2 of these identical objects in the list, it will only remove the first one - not literally whatever the first item in the list is. Can you provide an example which is not working the way you expect? – takendarkk Feb 13 '17 at 16:52
  • are these 2 object different in any way? why would you need to keep specifically one fo the 2? – Zeromus Feb 13 '17 at 16:59
  • Without getting too far into implementation, these objects are OrderProducts. I have found that OrderProducts are treated as equal when they are the same product, but I need to check additional attributes (Lists of customizations) in order to determine equality. – Otterman Feb 13 '17 at 17:09
  • For that you need to override the equals() and hashcode() methods of your OrderProducts class - those methods determine when objects are "the same" as per whatever your definition is. – takendarkk Feb 13 '17 at 17:45

1 Answers1

1

In Java, List uses equals() for its contains and remove(Object o) method as stated here

In one of the answer comments it is also stated that Java uses reference comparison as default.

Maybe you can override the equals() method for your products to get what you want.

Community
  • 1
  • 1
  • Thanks! Turns out adding the additional logic within the overridden equals() was exactly what I needed; I was thinking about the problem incorrectly. – Otterman Feb 13 '17 at 21:01