【问题标题】:How to create a Multidimensional ArrayList in Java?如何在 Java 中创建多维 ArrayList?
【发布时间】:2011-05-23 01:24:03
【问题描述】:

无论如何,我对 ArrayLists 还是很陌生,但我需要它们来完成这个项目,如果你们能帮助我,我将不胜感激!
基本上,我需要创建一个多维 ArrayList 来保存字符串值。我知道如何使用标准数组执行此操作,例如 public static String[][] array = {{}} 但这不好,因为我不知道数组的大小,我只知道它将有多少个维度。

所以,如果你们知道如何制作“具有 2/+ 维度的可动态调整大小的数组”,请告诉我。

提前致谢,
安迪

编辑/更新


也许使用变量调整或定义标准数组会更容易?但我不知道?
不过,使用我最初的 ArrayList 想法可能更容易......我只需要一个完整的示例代码来创建一个 2D ArrayList 并在不知道索引的情况下将示例值添加到两个维度。

【问题讨论】:

标签: java multidimensional-array arraylist


【解决方案1】:
ArrayList<ArrayList<Integer>> C = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> a = new ArrayList<Integer>();
        a.addAll(Arrays.asList(7, 3));
        ArrayList<Integer> b = new ArrayList<Integer>();
        b.addAll(Arrays.asList(2, 1));
        ArrayList<Integer> c = new ArrayList<Integer>();
        c.addAll(Arrays.asList(4, 9));
        C.addAll(Arrays.asList(a, b, c));

C.forEach(System.out::print);

【讨论】:

    【解决方案2】:

    对于那些想要预先初始化列表的人来说,这里是一个答案。需要 Java 8+。

    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.stream.IntStream;
    
    class Scratch {
    
      public static void main(String[] args) {
        int M = 4;
        int N = 3;
    
        // preinitialized array (== list of lists) of strings, sizes not fixed
        List<List<String>> listOfListsOfString = initializeListOfListsOfT(M, N, "-");
        System.out.println(listOfListsOfString);
    
        // preinitialized array (== list of lists) of int (primitive type), sizes not fixed
        List<List<Integer>> listOfListsOfInt = initializeListOfListsOfInt(M, N, 7);
        System.out.println(listOfListsOfInt);
      }
    
      public static <T> List<List<T>> initializeListOfListsOfT(int m, int n, T initValue) {
        return IntStream
            .range(0, m)
            .boxed()
            .map(i -> new ArrayList<T>(IntStream
                .range(0, n)
                .boxed()
                .map(j -> initValue)
                .collect(Collectors.toList()))
            )
            .collect(Collectors.toList());
      }
    
      public static List<List<Integer>> initializeListOfListsOfInt(int m, int n, int initValue) {
        return IntStream
            .range(0, m)
            .boxed()
            .map(i -> new ArrayList<>(IntStream
                .range(0, n)
                .map(j -> initValue)
                .boxed()
                .collect(Collectors.toList()))
            )
            .collect(Collectors.toList());
      }
    }
    

    输出:

    [[-, -, -], [-, -, -], [-, -, -], [-, -, -]]
    [[7, 7, 7], [7, 7, 7], [7, 7, 7], [7, 7, 7]]
    

    想知道IntStream的人的旁注:

    IntStream
        .range(0, m)
        .boxed()
    

    等价于

    Stream
        .iterate(0, j -> j + 1)
        .limit(n)
    

    【讨论】:

      【解决方案3】:

      你也可以这样做......

      • 首先创建并初始化矩阵或多维数组列表

        ArrayList<ArrayList<Integer>> list; MultidimentionalArrayList(int x,int y) { list = new ArrayList<>(); for(int i=0;i<=x;i++) { ArrayList<Integer> temp = new ArrayList<>(Collections.nCopies(y+1,0)); list.add(temp); } }

        • 在特定位置添加元素 void add(int row,int column,int val) { list.get(row).set(column,val); // list[row][column]=val }

        如果检查该行并且这个静态矩阵可以变为动态矩阵 列超出范围。只需为行插入额外的临时数组列表

        • 移除元素

        int remove(int row, int column) { return list.get(row).remove(column);// del list[row][column] }

      【讨论】:

        【解决方案4】:

        代码的功劳归于 JAcob Tomao。 我只是添加了一些cmets来帮助像我这样的初学者理解它。 希望对你有帮助。

        // read about Generic Types In Java & the use of class<T,...> syntax
        // This class will Allow me to create 2D Arrays that do not have fixed sizes    
        class TwoDimArrayList<T> extends ArrayList<ArrayList<T>> {
            public void addToInnerArray(int index, T element) {
                while (index >= this.size()) {
                    // Create enough Arrays to get to position = index
                    this.add(new ArrayList<T>()); // (as if going along Vertical axis)
                }
                // this.get(index) returns the Arraylist instance at the "index" position
                this.get(index).add(element); // (as if going along Horizontal axis)
            }
        
            public void addToInnerArray(int index, int index2, T element) {
                while (index >= this.size()) {
                    this.add(new ArrayList<T>());// (as if going along Vertical
                }
                //access the inner ArrayList at the "index" position.
                ArrayList<T> inner = this.get(index);
                while (index2 >= inner.size()) {
                    //add enough positions containing "null" to get to the position index 2 ..
                    //.. within the inner array. (if the requested position is too far)
                    inner.add(null); // (as if going along Horizontal axis)
                }
                //Overwrite "null" or "old_element" with the new "element" at the "index 2" ..
                //.. position of the chosen(index) inner ArrayList
                inner.set(index2, element); // (as if going along Horizontal axis)
            }
        }
        

        【讨论】:

          【解决方案5】:

          对于 3D ArrayList,您会怎么看 - 可以类似地使用 数组 - 查看代码中的 cmets:

              import java.util.ArrayList;
              import java.util.List;
          
              /**
               * ArrayList3D simulates a 3 dimensional array,<br>
               * e.g: myValue = arrayList3D.get(x, y, z) is the same as: <br>
               *      myValue = array[x][y][z] <br>
               * and<br>
               *      arrayList3D.set(x, y, z, myValue) is the same as:<br> 
               *      array[x][y][z] = myValue; <br>
               * but keeps its full ArrayList functionality, thus its
               * benefits of ArrayLists over arrays.<br>
               * <br>
               * @param <T> data type
               */
              public class ArrayList3D <T> {
          
                  private final List<List<List<T>>> arrayList3D;
          
                  public ArrayList3D() {
                      arrayList3D = newArrayDim1();
                  }
          
          
                                                      /**
                                                       * Get value of the given array element.<br>
                                                       * E.g: get(2, 5, 3);<br>
                                                       * For 3 dim array this would equal to:<br>
                                                       *      nyValue = array[2][5][3];<br>
                                                       * <br>
                                                       * Throws: IndexOutOfBoundsException
                                                       * - if any index is out of range 
                                                       *   (index < 0 || index >= size())<br>
                                                       * <br>
                                                       * @param dim1 index of the first dimension of the array list
                                                       * @param dim2 index of the second dimension of the array list
                                                       * @param dim3 index of the third dimension of the array list
                                                       * @return value of the given array element (of type T)
                                                       */
                  public T get(int dim1, int dim2, int dim3) {
                      List<List<T>>       ar2 = arrayList3D.get(dim1);
                      List<T>             ar3 = ar2.get(dim2);
                      return ar3.get(dim3);
                  }
          
          
                                                      /**
                                                       * Set value of the given array.<br>
                                                       * E.g: set(2, 5, 3, "my value");<br>
                                                       * For 3 dim array this would equal to:<br>
                                                       *      array[2][5][3]="my value";<br>
                                                       * <br>
                                                       * Throws: IndexOutOfBoundsException
                                                       * - if any index is out of range 
                                                       *   (index < 0 || index >= size())<br>
                                                       * <br>
                                                       * @param dim1 index of the first dimension of the array list
                                                       * @param dim2 index of the second dimension of the array list
                                                       * @param dim3 index of the third dimension of the array list
                                                       * @param value value to assign to the given array
                                                       * <br>
                                                       */
                  public void set(int dim1, int dim2, int dim3, T value) {
                      arrayList3D.get(dim1).get(dim2).set(dim3, value);
                  }
          
                                                      /**
                                                       * Set value of the given array element.<br>
                                                       * E.g: set(2, 5, 3, "my value");<br>
                                                       * For 3 dim array this would equal to:<br>
                                                       *      array[2][5][3]="my value";<br>
                                                       * <br>
                                                       * Throws: IndexOutOfBoundsException
                                                       * - if any index is less then 0
                                                       *   (index < 0)<br>
                                                       * <br>
                                                       * @param indexDim1 index of the first dimension of the array list
                                                       * @param indexDim2 index of the second dimension of the array list
                                                       *        If you set indexDim1 or indexDim2 to value higher
                                                       *        then the current max index,
                                                       *        the method will add entries for the
                                                       *        difference. The added lists will be empty.
                                                       * @param indexDim3 index of the third dimension of the array list
                                                       *        If you set indexDim3 to value higher
                                                       *        then the current max index,
                                                       *        the method will add entries for the
                                                       *        difference and fill in the values
                                                       *        of param. 'value'.
                                                       * @param value value to assign to the given array index
                                                       */
          
                  public void setOrAddValue(int indexDim1, 
                                            int indexDim2,
                                            int indexDim3, 
                                            T value) {
          
                      List<T> ar3 = setOrAddDim3(indexDim1, indexDim2);
          
                      int max = ar3.size();
          
                      if (indexDim3 < 0)
                          indexDim3 = 0;
                      if (indexDim3 < max)
                          ar3.set(indexDim3, value);
          
                      for (int ix = max-1; ix < indexDim3; ix++ ) {
                          ar3.add(value);
                      }
                  }
          
          
          
                  private List<List<List<T>>> newArrayDim1() {
                      List<T> ar3 = new ArrayList<>();
                      List<List<T>> ar2 = new ArrayList<>();
                      List<List<List<T>>> ar1 = new ArrayList<>();
                      ar2.add(ar3);
                      ar1.add(ar2);
                      return ar1;
                  }
          
                  private List<List<T>> newArrayDim2() {
                      List<T> ar3 = new ArrayList<>();
                      List<List<T>> ar2 = new ArrayList<>();
                      ar2.add(ar3);
                      return ar2;
                  }
          
                  private List<T> newArrayDim3() {
                      List<T> ar3 = new ArrayList<>();
                      return ar3;
                  }
          
          
                  private List<List<T>> setOrAddDim2(int indexDim1) {
          
                      List<List<T>> ar2 = null;
          
                      int max = arrayList3D.size();
                      if (indexDim1 < 0)
                          indexDim1 = 0;
                      if (indexDim1 < max)
                          return arrayList3D.get(indexDim1);
          
                      for (int ix = max-1; ix < indexDim1; ix++ ) {
                          ar2 = newArrayDim2();
                          arrayList3D.add(ar2);
                      }
                      return ar2;
          
                  }
          
                  private List<T> setOrAddDim3(int indexDim1, int indexDim2) {
          
                      List<List<T>> ar2 = setOrAddDim2(indexDim1);
                      List<T>       ar3 = null;
          
                      int max = ar2.size();
                      if (indexDim2 < 0)
                          indexDim2 = 0;
                      if (indexDim2 < max)
                          return ar2.get(indexDim2);
          
                      for (int ix = max-1; ix < indexDim2; ix++ ) {
                          ar3 = newArrayDim3();
                          ar2.add(ar3);
                      }
                      return ar3;
                  }
          
          
                  public List<List<List<T>>> getArrayList3D() {
                      return arrayList3D;
                  }
          
              }
          

          这是一个测试代码:

                  ArrayList3D<Integer> ar = new ArrayList3D<>();
          
                  int max = 3;
                  for (int i1 = 0; i1 < max; i1++) {
                      for (int i2 = 0; i2 < max; i2++) {
                          for (int i3 = 0; i3 < max; i3++) {
                              ar.setOrAddValue(i1, i2, i3, (i3 + 1) + (i2*max) + (i1*max*max));
                              int x = ar.get(i1, i2, i3);
                              System.out.println(" - " + i1 + ", " + i2 + ", " + i3 + " = " + x);
                          }
                      }
                  }
          

          结果输出:

          • 0, 0, 0 = 1
          • 0, 0, 1 = 2
          • 0, 0, 2 = 3
          • 0, 1, 0 = 4
          • 0, 1, 1 = 5
          • 0、1、2 = 6
          • 0, 2, 0 = 7
          • 0、2、1 = 8
          • 0、2、2 = 9
          • 1, 0, 0 = 10
          • 1、0、1 = 11
          • 1、0、2 = 12
          • 1, 1, 0 = 13
          • 1, 1, 1 = 14
          • 1、1、2 = 15
          • 1、2、0 = 16
          • 1、2、1 = 17
          • 1、2、2 = 18
          • 2, 0, 0 = 19
          • 2, 0, 1 = 20
          • 2, 0, 2 = 21
          • 2, 1, 0 = 22
          • 2, 1, 1 = 23
          • 2, 1, 2 = 24
          • 2, 2, 0 = 25
          • 2、2、1 = 26
          • 2, 2, 2 = 27

          【讨论】:

            【解决方案6】:

            ArrayList&lt;ArrayList&lt;String&gt;&gt; array = new ArrayList&lt;ArrayList&lt;String&gt;&gt;();

            根据您的要求,您可以使用如下所示的通用类来简化访问:

            import java.util.ArrayList;
            
            class TwoDimentionalArrayList<T> extends ArrayList<ArrayList<T>> {
                public void addToInnerArray(int index, T element) {
                    while (index >= this.size()) {
                        this.add(new ArrayList<T>());
                    }
                    this.get(index).add(element);
                }
            
                public void addToInnerArray(int index, int index2, T element) {
                    while (index >= this.size()) {
                        this.add(new ArrayList<T>());
                    }
            
                    ArrayList<T> inner = this.get(index);
                    while (index2 >= inner.size()) {
                        inner.add(null);
                    }
            
                    inner.set(index2, element);
                }
            }
            

            【讨论】:

            • 你应该参数化内部的ArrayList。
            • @Poindexter 感谢您提供编译警告。 :)
            • 一如既往,感谢您的快速回复,我只评论这个答案,因为它是最后一个。
            • 嗨,我又来了,只是想知道我如何将值添加到不同的维度。即 [1] = 字符串 1 [2] = 字符串 2
            • 对不起,我没有看到你的编辑!谢谢,但我不太清楚你的意思,也许代码示例可能会有所帮助?
            【解决方案7】:

            一旦我需要 2-D arrayList 并使用 List 和 ArrayList 创建,代码如下:

            import java.util.*;
            
            public class ArrayListMatrix {
            
                public static void main(String args[]){
            
                    List<ArrayList<Integer>> a = new ArrayList<>();
            
                    ArrayList<Integer> a1 = new ArrayList<Integer>();
                    ArrayList<Integer> a2 = new ArrayList<Integer>();
                    ArrayList<Integer> a3 = new ArrayList<Integer>();
            
            
                    a1.add(1);
                    a1.add(2);
                    a1.add(3);
            
                    a2.add(4);
                    a2.add(5);
                    a2.add(6);
            
                    a3.add(7);
                    a3.add(8);
                    a3.add(9);
            
                    a.add(a1);
                    a.add(a2);
                    a.add(a3);
            
            
                    for(ArrayList obj:a){
            
                        ArrayList<Integer> temp = obj;
            
                        for(Integer job : temp){
                            System.out.print(job+" ");
                        }
                        System.out.println();
                    }
                }
            }
            

            输出:

            1 2 3

            4 5 6

            7 8 9

            来源:https://www.codepuran.com/java/2d-matrix-arraylist-collection-class-java/

            【讨论】:

              【解决方案8】:

              如果允许您使用预定义的 Java 类,您可以执行以下操作:

              private static ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
              

              然后您可以添加新元素,例如:

              ArrayList<String> temp = new ArrayList<String>(); // added () 
              temp.add("Hello world.");
              biDemArrList.add(temp);
              

              希望您能理解我的意思以及发生了什么。此外,您需要导入 java.util.ArrayList;为此,如果您正在使用 Java 类。

              【讨论】:

                【解决方案9】:

                List&lt;ArrayList&lt;String&gt;&gt; 2dlist = new ArrayList&lt;ArrayList&lt;String&gt;&gt;(); 不是更好(更高效)的实现吗?

                【讨论】:

                • 如果您要在外部声明 List,似乎您也希望在内部声明 List&lt;List&lt;String&gt;&gt;
                • ArrayList 是 List 的特定实现……在内部使用 List 不会定义实现,而在外部使用 ArrayList 会迫使您始终使用该实现。在外部使用 List 意味着您可以稍后更改内部 ArrayList 而无需更改您在外部使用 List 的任何地方……请参阅:stackoverflow.com/questions/2279030/…>。
                • 实际上,@ErickG.Hagstrom 是正确的。 geowar 发布的答案支持 Erick 的答案。
                【解决方案10】:

                我可以想到一个数组内的数组或Guava's MultiMap

                例如

                ArrayList<ArrayList<String>> matrix = new ArrayList<ArrayList<String>>();
                

                【讨论】:

                • 当然不是Multimap。这是一个类似地图的结构,而不是类似列表的结构。
                【解决方案11】:
                【解决方案12】:

                您可以让 ArrayList 包含 ArrayLists 本身的元素。

                【讨论】:

                  猜你喜欢
                  • 2017-04-08
                  • 2015-09-26
                  • 2018-10-20
                  • 2014-02-26
                  • 1970-01-01
                  • 1970-01-01
                  • 2019-09-26
                  • 1970-01-01
                  • 2013-09-21
                  相关资源
                  最近更新 更多