当我在 Java 中使用数组列表时遇到一个小问题。本质上我希望将数组存储在数组列表中。我知道 arraylists 可以保存对象,所以它应该是可能的,但我不确定如何。
在大多数情况下,我的数组列表(从文件中解析)仅将一个字符作为字符串保存,但偶尔它会包含一系列字符,如下所示:
myarray
0 a
1 a
2 d
3 g
4 d
5 f,s,t
6 r
大多数时候,我唯一关心的字符串中位于位置 5 的字符是 f,但有时我可能还需要查看 s 或 t。我的解决方案是制作一个像这样的数组:
subarray
0 f
1 s
2 t
并将子数组存储在位置 5 中。
myarray
0 a
1 a
2 d
3 g
4 d
5 subarray[f,s,t]
6 r
我尝试使用以下代码执行此操作:
//for the length of the arraylist
for(int al = 0; al < myarray.size(); al++){
//check the size of the string
String value = myarray.get(al);
int strsz = value.length();
prse = value.split(dlmcma);
//if it is bigger than 1 then use a subarray
if(strsz > 1){
subarray[0] = prse[0];
subarray[1] = prse[1];
subarray[2] = prse[2];
}
//set subarray to the location of the string that was too long
//this is where it all goes horribly wrong
alt4.set(al, subarray[]);
}
但这并没有按照我想要的方式工作。它不允许我 .set(int, array)。它只允许 .set(int, string)。有人有建议吗?
最佳答案
最简单的方法是使用 ArrayList 的 ArrayList。
ArrayList<ArrayList<String>> alt4 = new ArrayList<ArrayList<String>>();
但是,这可能不是最好的解决方案。您可能需要重新考虑您的数据模型并寻找更好的解决方案。
关于java - 在数组列表中存储对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12943270/