填充二维数组

Filling 2d array

好吧,这可能是一个非常简单的解决方案,但我似乎找不到。我有两个 ArrayLists:

ArrayList<Candidate>partyList and ArrayList<Party>electoralList 

现在我想制作一个代表政党和候选人的 2d int 数组,如下所示:

p c
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3 
etc.

我想我已经有了正确的 for 循环来填充数组,但我只是错过了正确的公式。

int[][]ArrList;
for (int i=0; i<parties.size(); i++){ 
        for(int j=0; j<parties.get(i).getPartyList().size(); j++){
            ArrList[i][j]=

for循环真的正确吗?那么填充数组的公式是什么?

首先,ArrList不应该有首字母大写(它不是class而是一个对象)。

第二点(我认为让你烦恼的是)你没有初始化矩阵并且 parties.size() 始终为 0。我不确定,因为没有足够的代码。 你可以这样做

    int ROWS = 10;
    int COLS = 2;
    int [][] matrix = new int[ROWS][];
    for(int i=0; i< matrix.length; i++){
        matrix[i] = new int[COLS];
    }

或者,使用列表

    int ROWS = 10;
    int COLS = 2;
    List<List<Object>> matrix = new ArrayList<>(ROWS);
    for (int i = 0; i < ROWS; i++) {
        ArrayList<Object> row = new ArrayList<>(COLS);
        for (int j = 0; j < COLS; j++) {
            row.add(new Object());
        }
        matrix.add(row);
    }

我会尝试根据我对您在这里寻找的内容的理解来回答问题。

  • 你应该先了解一下:
  • 二维数组由嵌套数组组成,即 ArrList[2][3] = [ [1,2,3], [1,2,3] ] -> 第一个数字声明有多少个数组作为元素,第二个数字声明大小或者如果你喜欢的话:数组元素的长度

  • 如果您正在寻找用数字表示候选人和政党。这是我的解决方案:

    int[][]ArrList = new int[parties.size()][electoral.size()]
    for (int depth=0; depth < parties.size(); depth++){ 
        for(int itemIndex=0; itemIndex<parties.get(depth).getPartyList().size(); itemIndex++){
            ArrList[depth][itemIndex]= itemIndex;
    

希望这就是您要找的。

int[][] arrList=new int[parties.size()][2];
    int i=0,j=0,k=0;
    for(;i<parties.size();i++,j++){
        if(j==1){
            arrList[k][j]=electoralList .get(--i);
            j=-1;
            k++;
        }
        else{
            arrList[k][j]=parties.get(i);
        }
    }
    arrList[k][j]=aarM.get(electoralList .size()-1);
System.out.println(Arrays.deepToString(arrList));