首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java --如何在多维数组中添加元素?

问Java --如何在多维数组中添加元素?
EN

Stack Overflow用户
提问于 2015-05-21 18:22:10
回答 4查看 2K关注 0票数 1

我有一个数组:ArrayList<ArrayList<Integer>> items = new ArrayList<ArrayList<Integer>>();

我想在for冰柱上创建这个数组,其结果必须如下所示:

代码语言:javascript
复制
[0]: {0 , 0, 0, 3};
[1]: {1 , 2, 3, 3};
[2]: {6 , 2, 5, 4};

在ArrayList期间,必须在特定的index中向index添加新的值。index可以包含值或不包含值,但它们不能被重写。

我能否只向index (如items.add(index, array); )添加数组?

那么,如何在不覆盖任何内容的情况下添加更多的值呢?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2015-05-21 19:06:37

据我所理解,在循环的每一次迭代中,您都将有一个索引和一个整数。如果存在整数,则希望在指定索引处将整数插入到ArrayList中。或者你是在二维数组上循环?

考虑使用HashMap,其中键是索引(Integer),值是ArrayList:

代码语言:javascript
复制
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);
}
票数 0
EN

Stack Overflow用户

发布于 2015-05-21 18:26:20

最好的解决方案是使用HashMap,如下所示:

代码语言:javascript
复制
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});

然后,您可以在任何给定的键上设置和获取任何值,即使该键还不存在。

你可以用:

代码语言:javascript
复制
int[] row = items.get(0);

以获得所需的行。

票数 1
EN

Stack Overflow用户

发布于 2015-05-21 19:01:50

如果我正确理解,您将尝试将整个整数数组添加到ArrayList>中。在这种情况下,您可以尝试这样的方法:

代码语言:javascript
复制
    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中,而不是单独添加。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30381517

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档