字符串数组的 ArrayList [英] ArrayList of String Arrays
问题描述
我想做这样的事情:
private ArrayList<String[]> addresses = new ArrayList<String[3]>();
这似乎不起作用.在数组中存储每个地址有 3 个字段的多个地址而不为其创建单独的类的最简单方法是什么?
This does not seem to work. Whats the easiest way of storing multiple addresses with 3 fields per address in an array without creating a separate class for it?
推荐答案
对 3 个字符串使用第二个 ArrayList,而不是原始数组.即private List
>地址 = 新的 ArrayList
>();
Use a second ArrayList for the 3 strings, not a primitive array. Ie.
private List<List<String>> addresses = new ArrayList<List<String>>();
然后你可以:
ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");
addresses.add(singleAddress);
(我认为这里的类型擦除可能会发生一些奇怪的事情,但我认为这不重要)
(I think some strange things can happen with type erasure here, but I don't think it should matter here)
如果您一味地使用原始数组,则只需稍作改动即可使您的示例工作.正如其他答案中所解释的,数组的大小不能包含在声明中.如此变化:
If you're dead set on using a primitive array, only a minor change is required to get your example to work. As explained in other answers, the size of the array can not be included in the declaration. So changing:
private ArrayList<String[]> addresses = new ArrayList<String[3]>();
到
private ArrayList<String[]> addresses = new ArrayList<String[]>();
会起作用.
这篇关于字符串数组的 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!