required java.util.ArrayList,found java.lang.Object : I do not understand the reason for this error

前端 未结 7 1279
逝去的感伤
逝去的感伤 2021-01-28 09:30

Following are some snippets from a jsp page:

<%! ArrayList songList = new ArrayList(); %>

    <%
        songList = StoreSongLink.linkLis         


        
相关标签:
7条回答
  • 2021-01-28 10:08

    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.

    0 讨论(0)
  • 2021-01-28 10:09
    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){
    }
    
    0 讨论(0)
  • 2021-01-28 10:13
    for (ArrayList<String> list : songList){}
    

    must be

    for (Object list : songList){}
    

    Because songList declared type is ArrayList(equal ArrayList)

    0 讨论(0)
  • 2021-01-28 10:15

    Use:

    for (String s: songList) {
      // etc.
    }
    

    Also ensure that StoreSongLink.linkList is of type ArrayList<String>.

    0 讨论(0)
  • 2021-01-28 10:18

    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>();

    0 讨论(0)
  • 2021-01-28 10:21

    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 Objects, 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 Strings. 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.

    0 讨论(0)
提交回复
热议问题