[英]How to create (and then get elements) array / list of Lists?
How to create array or list of Lists in Java? 如何在Java中创建数组或列表列表?
I have: 我有:
List<Item> rows = new ArrayList<Item>();
rows.add(new Item("a"));
rows.add(new Item("b"));
... and how to create array of lists like this above? ...以及如何创建上述的列表数组?
List<Item> lists[] = {};
lists[0] = rows;
Here is what I am trying to do: 这是我正在尝试做的事情:
public class MainActivity extends FragmentActivity {
public static List<List<Item>> lists;
String tabs[] = { "Tab 1", "Tab 2" };
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lists = new ArrayList<List<Item>>();
for (int i = 0; i < tabs.length; i++)
{
lists.add(i, init());
}
}
public List<Item> init()
{
List<Item> rows = new ArrayList<Item>();
rows.add(new Item("test"));
return rows;
}
}
... and then I am trying to get that list by using: ...然后我尝试使用以下方法获取该列表:
MainActivity.lists.get(0);
You should not create an array of generics types, because it's not type safe . 您不应该创建泛型类型的数组,因为它的类型不是safe 。 Here's a quote from that link
这是该链接的报价
Parameterized types do not have exact runtime type information.
参数化类型没有确切的运行时类型信息。 As a consequence, the array store check does not work because it uses the dynamic type information regarding the array's (non-exact) component type for the array store check.
结果, 数组存储检查不起作用,因为它使用有关数组(非精确)组件类型的动态类型信息进行数组存储检查。
Emphasis mine. 强调我的。
Basically, array uses a store check at runtime, to check whether the elements stored in it, is compatible with the type of actual array. 基本上,数组在运行时使用存储检查来检查存储在其中的元素是否与实际数组的类型兼容 。 Now, since a generic type doesn't have actual type information at runtime due to type erasure , the array store check won't work.
现在,由于泛型由于类型擦除而在运行时没有实际的类型信息,因此数组存储检查将不起作用。
Eg (Taken from the above link): 例如(摘自上面的链接):
Pair<Integer,Integer>[] intPairArr = new Pair<Integer,Integer>[10]; // illegal
Object[] objArr = intPairArr;
objArr[0] = new Pair<String,String>("",""); // should fail, but would succeed
It would work because Pair<Integer, Integer>[]
, is actually Pair[]
at runtime, and will successfully store Pair<String, String>
, which is also a Pair
at runtime. 之所以会这样,是因为
Pair<Integer, Integer>[]
实际上在运行时是Pair[]
,并且会成功存储Pair<String, String>
(在运行时也是Pair
。
But that would fail further in your code, once you try to fetch elements from array. 但是,一旦您尝试从数组中获取元素,这将在代码中进一步失败。
So, you should rather create a list of list : 因此,您应该创建一个list 列表 :
List<List<Item>> itemList = new ArrayList<List<Item>>();
itemList.add(rows);
This is how you can create List of List 这是创建列表列表的方法
List<List<Item>> listOfList = new ArrayList<List<Item>>();
listOfList.add(new ArrayList<Item>());
listOfList.get(0).add(new Item());
and List of array 和数组列表
List<Item[]> listOfArray = new ArrayList<Item[]>();
listOfArray.add(new Item[] { item1, item2});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.