Malaikatu Kargbo
Malaikatu Kargbo

Reputation: 313

Set have the same erasure, yet neither overrides the other error

My homework was to basically rewrite the methods for a set so it's usable for for a custom class I created called Square. I keep getting the error:

error: name clash: removeAll(Collection<Square>) in SquareSet and removeAll(Collection<?>) in Set have the same erasure, yet neither overrides the other
public boolean removeAll(Collection<Square> objects) {

I imported both Set and Collection at the beginning of my code and the class SquareSet implements Set<Square>.

    public boolean removeAll(Collection<Square> objects) {
    Square[] newSet;
    int count = 0;
    for(Square each : objects) {
        count -= 1;
        newSet = new Square[(daSet.length)-count];
        for (int i = 0; i < daSet.length; i++) {
            if (daSet[i].equals(each)) {
                if(i == 0) {
                    for (int j = 1; j < daSet.length ; j++) {
                        newSet[j - 1] = daSet[j];
                    }
                } else if (i == ((daSet.length) - 1)) {
                    for (int j = 0; j < daSet.length ; j++) {
                        newSet[j] = daSet[j];
                    }
                } else {
                    for (int j = 0; j < i; j++) {
                    newSet[j] = daSet[j];
                    }
                    for (int j = i; j < newSet.length; j++){
                    newSet[j] = daSet[j+1];
                    }
                }
            }
        }
    }

I understand a method is overloaded instead of overwritten when the parameter is different from the parameter type I'm overwriting. But I still don't understand why I'm getting this error.

Upvotes: 0

Views: 584

Answers (1)

rgettman
rgettman

Reputation: 178263

Because you're implementing Set<Square>, you'd naturally expect the removeAll method to be removeAll(Collection<Square>), but unfortunately in the Set interface, the removeAll method is removeAll(Collection<?>), with a wildcard instead of the generic type parameter. This causes your error -- Collection<Square> is incompatible with Collection<?>.

As for why it's that way, this question deals with that. Basically, the designers couldn't get it to work properly when the remove-like methods were fully generified.

To implement the interface properly, you must have your parameter's type be Collection<?>. That means the type of each must be Object, and you'll have to type-check it to see if it's a Square.

In addition, you will want to size your new array more carefully, and only if you have a match to remove from your array.

Upvotes: 1

Related Questions