如何ArrayList的元素转移到一个二维数组? [英] How to transfer arrayList elements into a 2D array?

查看:263
本文介绍了如何ArrayList的元素转移到一个二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的ArrayList 名为列表<对GT&; patternList =新的ArrayList<>()包含了一些长度为2的模式,例如,对于A = {1,2,3,4}我创造一些像模式(1,3 )(3,2)...等。我希望把这些模式成一个二维数组(矩阵)[A] [A]的方式,模式必须进入一个特定的指数矩阵,比如图案(1,3)必须进入指数[3] [ 3]或图案(3,2)必须在[2] [2]。

I have an ArrayLists called List<Pair> patternList = new ArrayList<>() that contains a number of patterns of length 2. for example, for A={1,2,3,4} I create some patterns like (1,3)(3,2)...etc. I want to put these patterns into a 2d array(matrix)[A][A] in way that the patterns must go into a specific index in the matrix, For instance pattern (1,3) must go into index [3][3] or pattern (3,2) must go in [2][2].

感谢。

推荐答案

如果您只想把他们的第二个索引。 (编辑允许多个每个索引):

If you just want to put them in by the second index. (edited to allow multiple per index):

List<Pair>[][] matrix = new LinkedList<Pair>[5][5]; //Replace 5 here a getter for the maximum value of A
                                  //Here it's 5 because the max of your example is 4.
//Initialize all positions of matrix to empty list.
for (int r = 0; r < matrix.length; r++){
    for(int c = 0; c < matrix[r].length; c++){
        matrix[r][c] = new LinkedList<Pair>();
    }
}
for (Pair p : patternList){
    if (matrix[p.second][p.second] == null)
        matrix[p.second][p.second] = new LinkedList<Pair>();
    matrix[p.second][p.second].add(p);
}

这是不是真的使用阵列虽然的2D方面;你可以完成同样的事情用列表的一维数组:

This isn't really using the 2d aspect of the array though; you could accomplish exactly the same thing with a 1d array of lists:

List<Pair>[] arr = new LinkedList<Pair>[5]; //Replace 5 here a getter for the maximum value of A
                                  //Here it's 5 because the max of your example is 4.
//Initialize all positions of array to empty list.
for (int r = 0; r < matrix.length; r++){
    arr[r] = new LinkedList<Pair>();
}
for (Pair p : patternList){
    if (arr[p.second] == null)
        arr[p.second] = new LinkedList<Pair>();
    arr[p.second].add(p);
}

这篇关于如何ArrayList的元素转移到一个二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆