如何将arrayList元素转换为2D数组?

时间:2014-08-08 18:15:17

标签: java arrays arraylist

我有ArrayLists名为List<Pair> patternList = new ArrayList<>(),其中包含多个长度为2的模式。例如,对于A = {1,2,3,4}我创建了一些模式,如(1, 3)(3,2)...等。我想把这些模式放到二维数组(矩阵)[A] [A]中,模式必须进入矩阵中的特定索引,例如模式(1,3)必须进入索引[3] [ 3]或模式(3,2)必须进入[2] [2]。

感谢。

2 个答案:

答案 0 :(得分:1)

如果您只想将它​​们放入第二个索引中。 (编辑为允许每个索引多个):

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);
}

这并不是真正使用数组的第二方面;你可以用一列列表完成同样的事情:

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);
}

答案 1 :(得分:0)

由于您希望在每个位置保留多个元素,我建议您使用MultimapMultimap基本上是Map<Key, Collection<Value>>,负责为您创建集合。

Multimap

 Multimap<List<Integer>, Pair> myMap = ArrayListMultimap.create();

 for (Pair p : myPairs){
     List<Integer> key = Lists.newArrayList(p.second, p.second);
     myPair.put(key, p);
 }
相关问题