对于java中的数组和列表仍然有点新,我想动态地将元素添加到列表中,所以例如,如果我有这样的代码:
List<int[]> rowList = new ArrayList<int[]>();
rowList.add(new int[] { 1, 2, 3 });
rowList.add(new int[] { 4, 5, 6 });
rowList.add(new int[] { 7, 8 });
我如何动态添加1,2,3,4,5,6,7等?提前感谢您的帮助
答案 0 :(得分:2)
只需使用List<Integer>
直接存储号码:
List<Integer> ints = new ArrayList<Integer>();
ints.add(1); // works with Java 1.5+, inboxing
ints.add(2);
或者,如果要保留数据结构,请将数字换成短数组:
rowList.add(newValue(1));
我们有:
private int[] newValue(int a) {
int[] result = new int[1];
result[0] = a;
return result;
}
修改强>
使用varargs和autoboxing的Java 1.5+魔法:
private int[] newValue(Integer... values) {
int[] result = new int[values.length];
for (int i = 0; i < result.length; i++)
result[i] = values[i];
return result
}
<强>用法:强>
List<int[]> rowList = new ArrayList<int[]>();
rowList.add(newValues(10, 20, 30));
rowList.add(newValues(1,2,3,4,5,6,7));
答案 1 :(得分:0)
如果要在列表中添加新的int [],首先必须创建并填充它。如果你不知道数组的长度,我会建议一个数组,当你达到它的极限时会动态地增加空间。
创建此数组后,只需将其作为参数传递。应该是直截了当的。
答案 2 :(得分:0)
如果您想在不写出每个数字的情况下添加它们,可以使用for循环。
for(int i = 0; i < [however many you would like]; i++) {
ints.add(i);
}
答案 3 :(得分:0)
这种效果(如果你有JDK 5及更高版本,则使用varargs
。)
public class ListUtils {
public static void add(List<int[]> list, int... args) {
if (list != null && args != null) {
list.add(args);
}
}
}
现在,你可以做到
ListUtils.add(list, 1, 2, 3, 4, 5, 6, 7);
答案 4 :(得分:0)
我不确定你需要什么,但我希望这个例子可以帮助你:
List<Integer> rowList = new ArrayList<Integer>();
Collections.addAll(rowList, ArrayUtils.toObject(new int[] { 1, 2, 3 }));
Collections.addAll(rowList, ArrayUtils.toObject(new int[] { 4, 5, 6 }));
Collections.addAll(rowList, ArrayUtils.toObject(new int[] { 7, 8 }));
ArraysUtils是一类非常有用的处理原始和对象数组的apache公共文件。
此致 Diodfr