2

I have two arraylists declared like this:

ArrayList<Book> books=new ArrayList<Book>();
ArrayList<Painting> paintings=new ArrayList<Painting>();

Where Book and Painting are classes. I want to define a function addToList like this:

public void addToList(Object myObject)
    {
        if(myObject instanceof Book)
                 books.add(myObject);

        else if(myObject instanceof Painting)
                 paintings.add(myObject);
    }

But it shows an error saying that The method add(Painting) in the type ArrayList is not applicable for the arguments (Object)

The method add(Book) in the type ArrayList is not applicable for the arguments (Object)

Is there a way to get through this? Why is the error occurring anyway since I put each add statement in a if else loop confirming that the object of appropriate class shall be added to the respective arraylist?

I could have done this by splitting the add function into two different add functions with one as argument Painting myObject and other as Book myObject but I want to do it all in the same function. Can it be done?

1
  • You should use an IDE. Also for future question you could use the search feature, this question has probably a lot of duplicates.. Commented Apr 2, 2015 at 6:41

2 Answers 2

4

You need to cast the object first paintings.add((Painting)myObject);, the generic ArrayList<Painting> is forbidding you to add it, since it expects an inheritance of the class Painting and is throwing a compiler error, since the generell class Object doesn´t fulfill this condition

Sign up to request clarification or add additional context in comments.

1 Comment

Great! This works. Are there any drawback or overheads of casting?
2

Since you are using generics you are not allowed to do so, you need to cast it:

    if(myObject instanceof Book)
         books.add((Book)myObject);

    else if(myObject instanceof Painting)
         paintings.add((Painting)myObject);

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.