0

I have an arraylist

private ArrayList<Object> myList = new Arraylist<>()

This arraylist contains String values and SongInfoModel(object) values.

How to retrieve these two into their respective arraylists?

private ArrayList<SongInfoModel> songList = new Arraylist<>()

private ArrayList<String> path= new Arraylist<>()

I'm using below given code, but it is giving me error in the "add" statement

for(Object ob: myList){

        if(ob instanceof SongInfoModel)  {

            songList.add(ob); //error
        }else if(ob instanceof String){

            path.add(ob); //error
        }
    }

I know this is a noobish question, but please help me!

2
  • It might help posting (or reading if you haven't done so yet) the error. Also, are your lists named correctly? You use SongList once and songList the second time. Similarly, PathName and path seemingly interchangeably Commented Dec 27, 2017 at 15:18
  • You can cast the objects after the instanceof Commented Dec 27, 2017 at 15:20

1 Answer 1

2

You need to cast the Objects:

for(Object ob: myList){

        if(ob instanceof SongInfoModel)  {

            songList.add((SongInfoModel)ob); //<--
        }else if(ob instanceof String){

            path.add((String)ob); //<--
        }
    }
Sign up to request clarification or add additional context in comments.

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.