Following are some snippets from a jsp page:
<%! ArrayList songList = new ArrayList(); %>
<%
songList = StoreSongLink.linkLis
While you assign songList a new ArrayList, you're defining the songList as an arrayList (which is arrayList). That would make it okay to iterate over songList as Objects. But you're actually iterating over songList as ArrayList.
So in short, you need to switch songList to be decared to ArrayList and you need to iterate over songList with Strings, not ArrayList.
for (ArrayList<String> list : songList){} // Error is here
And you have define a reference of ArrayList of Object type and declared a String type ArrayList instance which should be ArrayList<String> songList = new ArrayList<String>();
or ArrayList<String> songList = new ArrayList();
(supports only java 7)
So the Corrected code could be like -
<%! List<String> songList = new ArrayList<String>(); %>
...
for (String list : songList){
}
for (ArrayList<String> list : songList){}
must be
for (Object list : songList){}
Because songList declared type is ArrayList(equal ArrayList)
Use:
for (String s: songList) {
// etc.
}
Also ensure that StoreSongLink.linkList
is of type ArrayList<String>
.
ArrayList
is, as you probably know, a raw type, when not using parametrized ArrayList<E>
declaration. So you effectively turned it to array list of Object
instead of String
, with your initialization:
ArrayList songList = new ArrayList<String>();
You should declare it explicitly at the start:
ArrayList<String> songList = new ArrayList<String>();
If you declare it like this:
ArrayList songList = new ArrayList<String>();
Then you are saying songList
is an ArrayList
of Object
s, regardless of what is to the right of the =
. Assignment doesn't change this, so this:
ArrayList songList = new ArrayList<String>();
songList = StoreSongLink.linkList;
does not change the type of songList
, it's still effectively ArrayList<Object>
.
If you fix the declaration, then your for
loop should look like:
for (String list : songList){}
Because songList
is array list of String
s. As you have it, Java extracts each Object
from songList
and tries to assign it to what you have declared to the left of :
, which you have told it is an ArrayList<String>
. It cannot convert the Object
to ArrayList<String>
(especially since the Object
is really just a String
underneath), so it throws an error.