String数组的ArrayList [英] ArrayList of String Arrays

查看:72
本文介绍了String数组的ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做类似的事情:

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,而不是原始数组。即。$
私人列表< List< String>> addresses = new ArrayList< List< String>>();

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[]>();

将有效。

这篇关于String数组的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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