JCoder
JCoder

Reputation: 189

Java: Extending ArrayList Using Objects

I'm extending ArrayList (not implementing an interface) in Java. I get an error in the function:

 public void push(Object o) {
    add(o);
}

It says "The method add(E) in the type ArrayList< E > is not applicable for the arguments. How can I fix this?

Upvotes: 1

Views: 844

Answers (2)

chiwangc
chiwangc

Reputation: 3577

As pointed out by @shikjohari you need to specify how you extend the ArrayList.

The reason you get this error is because you are trying to push an Object to an ArrayList that is expecting to get something of type E. So you need to explicitly cast the o to type E in order for this to work (of course, you need to ensure that o is indeed of dynamic type E before you perform casting).

Assuming E is a class defined somewhere else (it does not represent a generic type here, otherwise, the compiler should give you another error - "E cannot be resolved to a type" instead of "The method add(E) in the type ArrayList< E > is not applicable for the arguments"), you should have something like the following:

// This class is defined somewhere in your package
class E {

}

public class YourClass extends ArrayList<E> {   
    public void push(Object o) {
        if (o instanceof E) {
            add((E) o);
        }
    }
}

Upvotes: 1

shikjohari
shikjohari

Reputation: 2288

This works for me, I m not sure what you want to achieve with this.

public class MyList<E> extends ArrayList<E>{
     public void push(E o) {
            add(o);
        }
}

Upvotes: 1

Related Questions