我有一个 ArrayList 对象,我想向其动态添加 ArrayList。
但是,由于编译器在添加对象的循环运行之前不知道外部 ArrayList 中将包含哪些对象,因此我无法像往常一样使用内部 ArrayList。
我的代码看起来有点像这样:
ArrayList list = new ArrayList();
for(int i=8;i>0;i--)
{
list.add(i, new ArrayList());
}
for(int i=8;i>0;i--)
{
tileRows.get(i).add( //add other stuff );
}
我如何告诉编译器 list
中的项目将属于 ArrayList
类型?
请记住,我是 Java 的新手。如果这是一个愚蠢的问题,我深表歉意。
最佳答案
您可以声明一个 List<Whatever>
, 和 Whatever
可以是另一个支持泛型的接口(interface)/类,比如 List<String>
, 所以把所有这些放在一起你可以声明一个 List<List<String>>
编译器会很高兴。根据您上面的代码:
List<List<String>> tileRows= new ArrayList<List<String>>();
for(int i=8;i>0;i--) {
list.add(i, new ArrayList<String>());
}
for(int i=8;i>0;i--) {
//here the compiler knows tileRows.get(i) is a List<String>
tileRows.get(i).add("foo");
//uncomment the below line and you will get a compiler error
//tileRows.get(i).add(new Object());
}
记住永远program to an interface, not to a direct class implementation .
关于java - ArrayLists的ArrayList,如何使用内链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21991993/