required java.util.ArrayList<String>,found java.lang.Object : 我不明白这个错误的原因 [英] required java.util.ArrayList&lt;String&gt;,found java.lang.Object : I do not understand the reason for this error

查看:21
本文介绍了required java.util.ArrayList<String>,found java.lang.Object : 我不明白这个错误的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是jsp页面的一些片段:

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){}

%>

else srciplet 中的代码产生错误 required java.util.ArrayList找到 java.lang.Object.为什么是这样 ?我不明白这是什么原因.

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.

为什么编译器说 songList 是 Object 类型?

推荐答案

你应该在开始时明确声明:

You should declare it explicitly at the start:

ArrayList<String> songList = new ArrayList<String>();

如果你这样声明:

ArrayList songList = new ArrayList<String>();

那么你是说 songListObjectArrayList,不管 =.分配不会改变这一点,所以这个:

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;

不改变songList的类型,它仍然是有效的ArrayList.

does not change the type of songList, it's still effectively ArrayList<Object>.

如果您修正了声明,那么您的 for 循环应该如下所示:

If you fix the declaration, then your for loop should look like:

for (String list : songList){}

因为songListString 的数组列表.正如您所拥有的,Java 从 songList 中提取每个 Object 并尝试将其分配给您在 : 左侧声明的内容,您已经告诉它是一个 ArrayList.它不能将 Object 转换为 ArrayList(特别是因为 Object 实际上只是下面的 String),所以它会抛出一个错误.

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.

这篇关于required java.util.ArrayList<String>,found java.lang.Object : 我不明白这个错误的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆