Java-如何在多维arraylist上添加元素?
我有这个阵列:Java-如何在多维arraylist上添加元素?,java,arrays,multidimensional-array,Java,Arrays,Multidimensional Array,我有这个阵列: ArrayList items=新建ArrayList(); 我想在磁盘上为磁盘创建此数组,结果必须如下所示: [0]: {0 , 0, 0, 3}; [1]: {1 , 2, 3, 3}; [2]: {6 , 2, 5, 4}; ArrayList<ArrayList<Integer>> items = new ArrayList<ArrayList<Integer>>(); Integer[] intLis
ArrayList items=新建ArrayList();
我想在磁盘上为
磁盘创建此数组,结果必须如下所示:
[0]: {0 , 0, 0, 3};
[1]: {1 , 2, 3, 3};
[2]: {6 , 2, 5, 4};
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)));
在循环期间,必须在特定的索引中向ArrayList添加新值。索引可以包含值,也可以不包含值,但不能覆盖它们
我可以只将数组添加到某个索引
中,如项。添加(索引,数组)代码>
那么,如何在不覆盖任何内容的情况下添加更多值呢?items.get(i).add(j)代码>
其中i
和j
是整数。最佳解决方案是使用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});
获取所需行。如果我理解正确,您正在尝试将整个整数数组添加到ArrayList>。在这种情况下,您可以尝试以下操作:
[0]: {0 , 0, 0, 3};
[1]: {1 , 2, 3, 3};
[2]: {6 , 2, 5, 4};
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)));
ArrayList items=new ArrayList();
整数[]intList1={0,0,0,3};
整数[]intList2={1,2,3,3};
整数[]intList3={6,2,5,4};
添加(新的ArrayList(Arrays.asList(intList1));
添加(新的ArrayList(Arrays.asList(intList2));
添加(新的ArrayList(Arrays.asList(intList3));
或者,这些int数组可以添加到循环中的ArrayList中,而不是单独添加。据我所知,在循环的每次迭代中,都会有一个索引和一个整数。如果存在整数,则要将其插入指定索引处的ArrayList中。还是在二维数组上循环
考虑使用HashMap,其中键是索引(整数),值是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);
}
HashMap items=newhashmap();
//给定一个索引i和一个整数n
//(例如,在对数据进行循环时获得):
如有(第(i)项){
//HasMap在此索引/键处包含一个ArrayList
//将号码添加到列表的末尾
项目。获取(i)。添加(n);
}否则{
//此索引/键处尚未存储ArrayList
//创建仅包含编号的新列表
ArrayList=新建ArrayList();
列表。添加(n);
项目。放置(i,列表);
}
即使索引不存在,也可以这样做?(在第一次添加时)不,您需要先添加一个空的ArrayList来创建它