Sajad
Sajad

Reputation: 2363

Remove from arraylist by value

I implement the equals() to be able to remove an array list elements by value:

public boolean equals(Object obj) {
    if (obj == null) return false;
    if (obj == this) return true;
    if (!(obj instanceof Character)) return false;
    Character ch = (Character) obj;
    return ch.equals(this);
}

And this is my arraylist:

static ArrayList<Character> sr = new ArrayList<Character>();

contains:

Sr: [a, b, c, d, e, f, g]

I'm going to remove a and b characters:

public static removeChars(){

    ...
    sr.remove('a');
    sr.remove('b');

}

But always two last items (g and f) had been deleted.

Upvotes: 0

Views: 220

Answers (1)

sprinter
sprinter

Reputation: 27956

If you are using java.lang.Character in your ArrayList then you shouldn't need to implement equals. If it is your own Character then the call to remove is not creating objects of your class - it's creating standard Character objects which is why they don't equal the items in the list.

If this is the problem then you need to ensure you pass instances of your class to the call to remove rather than relying on autoboxing:

sr.remove(new Character('a'));

Alternatively if you are using Java 8 you could explicitly implement an equalsChar method and call it in a predicate:

sr.removeIf(c -> c.equalsChar('a'));

This has the advantage of removing all instances (not just the first one) which is often what is required for a List rather than a Set.

Upvotes: 2

Related Questions