Add Multidimensinal array to an array list using Java

情到浓时终转凉″ 提交于 2020-01-06 18:04:54

问题


I am having a method(function) that is supposed to add a (8*6)Array to an Array list. Function is called several times.

int [][] KeySelection = new int [8][7];

  for(int i=0;i<KeySelection.length;i++){
  for(int j=0;j<KeySelection[0].length;j++){
      KeySelection[i][j] = (int) (Math.random () * 2);

     }
  }

Each time this function is called a totally new KeySelection Array is done. What i need now is to declare an array list so that it could store all the KeySelection Arrays in that list.

So that when i need the first KeySelection Table i could find it in the first index of the Array list. Could somebody Help


回答1:


Create an ArrayList of type int[][]: -

List<int[][]> list = new ArrayList<int[][]>();

And then, add your array to this list after creation: -

list.add(keySelection);

NOTE: - Variable name should start with lowercase letters.




回答2:


Since arrays in Java are special type of objects, you can use an ArrayList of objects to hold your arrays. Declare your list like that and populate it via for loop etc.

ArrayList<int[][]> list = new ArrayList<int[][]>();


来源:https://stackoverflow.com/questions/13430448/add-multidimensinal-array-to-an-array-list-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!