【发布时间】:2017-12-27 01:39:19
【问题描述】:
我是Collection Framework 的新手。我正在使用ArrayList() 运行Java 程序。当我尝试循环它以获取它的元素时,它会抛出类似
HelloWorld.java:15: error: cannot find symbol
for(int k=0;k<al.length;k++)
^
symbol: variable length
location: variable al of type ArrayList<String>
HelloWorld.java:17: error: array required, but ArrayList<String> found
System.out.println("elements are"+al[k]);
这是我写的代码。
import java.util.ArrayList;
public class HelloWorld{
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("pen");
al.add("pencil");
al.add("ink");
al.add("notebook");
al.add("book");
al.add("books");
al.add("paper");
al.add("white board");
for(int k=0;k<al.length;k++)
{
System.out.println("elements are"+al[k]);
}
}
}
帮我指出我的错误。提前致谢
【问题讨论】:
-
ArrayList中没有length字段,需要调用al.size()方法
-
arraylist 有 size 属性而不是 length
-
然后你不能使用索引器,你必须使用
get。 -
使用 al.size() 和 al.get(k)
-
优雅地使用
foreach或stream