2

Say I have an object which has an id: String and name: String field.

If I have an array of these objects, if I use the remove method, since technically the Object pointer is different, the object I want won't get removed.

Ex:

List<ObjectA> newList = new ArrayList<>();
// Objecta1(id: a, name: a)
// Objecta2(id: b, name: b)
// Objecta3(id: b, name: b)
newList.add(objecta1);
newList.add(objecta2);
newList.remove(objecta3); --> will equal false

What is the cleanest way to have remove do this correctly?

I searched around and found that I could use removeIf and do a comparison there. I also could use an Iterator and then compare the fields myself. Just wondering if there is a canonical, clean way of doing it in Java. Thanks.

3
  • 7
    Does ObjectA override equals()? Commented Jan 26, 2017 at 7:18
  • @Eran -- hey so that's what i was thinking of doing. i was just wondering if that was the cleanest way to structure this? Commented Jan 26, 2017 at 7:23
  • Yes, you should use an equals method instead of a custom comparison or something. After all, you're checking if two objects should be considered equal. You should probably override equals anyway; a lot of methods use it. Commented Jan 26, 2017 at 7:27

2 Answers 2

3

Beside the solution override equals, you can do it with java 8:

newList.removeIf(p -> p.getId().equals(objecta3.getId()));
Sign up to request clarification or add additional context in comments.

Comments

3

Your object should @Override the equals method.

Add the following to your class:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof ObjectA)) return false;

    ObjectA objectA = (ObjectA) o;

    if (getId() != objectA.getId()) return false;
    return getName() != null ? getName().equals(objectA.getName()) : objectA.getName() == null;

}

@Override
public int hashCode() {
    int result = getId();
    result = 31 * result + (getName() != null ? getName().hashCode() : 0);
    return result;
}

and then:

while(newList.remove(objecta3)){};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.