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?