我有一个数组:ArrayList<ArrayList<Integer>> items = new ArrayList<ArrayList<Integer>>();
我想在for冰柱上创建这个数组,其结果必须如下所示:
[0]: {0 , 0, 0, 3};
[1]: {1 , 2, 3, 3};
[2]: {6 , 2, 5, 4};在ArrayList期间,必须在特定的index中向index添加新的值。index可以包含值或不包含值,但它们不能被重写。
我能否只向index (如items.add(index, array); )添加数组?
那么,如何在不覆盖任何内容的情况下添加更多的值呢?
发布于 2015-05-21 19:06:37
据我所理解,在循环的每一次迭代中,您都将有一个索引和一个整数。如果存在整数,则希望在指定索引处将整数插入到ArrayList中。或者你是在二维数组上循环?
考虑使用HashMap,其中键是索引(Integer),值是ArrayList:
HashMap<Integer, ArrayList<Integer>> items = new HashMap<>();
// Given an index, i, and an integer, n
// (e.g. obtained while looping over your data):
if (items.containsKey(i)){
// Your HasMap contains an ArrayList at this index / key
// Add the number to the end of the list
items.get(i).add(n);
} else {
// There is no ArrayList stored yet at this index / key
// Create a new list containing only the number
ArrayList<Integer> list = new ArrayList<>();
list.add(n);
items.put(i, list);
}发布于 2015-05-21 18:26:20
最好的解决方案是使用HashMap,如下所示:
HashMap<Integer, int[]> items = new HashMap<Integer, int[]>();
items.put(0, new int[] {0 , 0, 0, 3});
items.put(1, new int[] {1 , 2, 3, 3});
items.put(2, new int[] {6 , 2, 5, 4});然后,您可以在任何给定的键上设置和获取任何值,即使该键还不存在。
你可以用:
int[] row = items.get(0);以获得所需的行。
发布于 2015-05-21 19:01:50
如果我正确理解,您将尝试将整个整数数组添加到ArrayList>中。在这种情况下,您可以尝试这样的方法:
ArrayList<ArrayList<Integer>> items = new ArrayList<ArrayList<Integer>>();
Integer[] intList1 = {0,0,0,3};
Integer[] intList2 = {1,2,3,3};
Integer[] intList3 = {6,2,5,4};
items.add(new ArrayList<Integer>(Arrays.asList(intList1)));
items.add(new ArrayList<Integer>(Arrays.asList(intList2)));
items.add(new ArrayList<Integer>(Arrays.asList(intList3)));或者可以在循环中将这些int数组添加到ArrayList中,而不是单独添加。
https://stackoverflow.com/questions/30381517
复制相似问题