Following are some snippets from a jsp page:
<%! ArrayList songList = new ArrayList<String>(); %>
<%
songList = StoreSongLink.linkList;
// linkList is a static variable in the class StoreSongLink
// There the linkList is defined as public static ArrayList<String> linkList = new ArrayList<String>();
%>
<%} else {
for (ArrayList<String> list : songList){}
%>
The code inside the else srciplet produces an error required java.util.ArrayList<String> found java.lang.Object. Why is this ? I do not understand the reason for this.
Why does the compiler say songList to be of type Object ?
You should declare it explicitly at the start:
If you declare it like this:
Then you are saying
songListis anArrayListofObjects, regardless of what is to the right of the=. Assignment doesn’t change this, so this:does not change the type of
songList, it’s still effectivelyArrayList<Object>.If you fix the declaration, then your
forloop should look like:Because
songListis array list ofStrings. As you have it, Java extracts eachObjectfromsongListand tries to assign it to what you have declared to the left of:, which you have told it is anArrayList<String>. It cannot convert theObjecttoArrayList<String>(especially since theObjectis really just aStringunderneath), so it throws an error.