1

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?

2
  • Please show some more code on how you are extending the arraylist. I hope you know what you are doing..:P Commented Feb 27, 2015 at 4:47
  • public void push(E o) { - But you have to ask the question why? Commented Feb 27, 2015 at 4:49

2 Answers 2

1

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);
        }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);
        }
    }
}

2 Comments

I assume E is a class defined somewhere else, it does not represent a generic type in this case. Otherwise, the compiler should give you another error - "E cannot be resolved to a type"
Thanks for giving it a look. shikjohari solved the problem :)

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.