如何制作动态2D数组并在其中存储经过改组的数组

时间:2018-11-17 02:56:16

标签: java arrays multidimensional-array dynamic shuffle

我创建了一个2D数组列表,该列表具有固定的数字或行数以及包含数字1-4的数组。我应该将数组改组,然后将该数组存储在arraylist中。但是,当我以后打印整个arraylist时,它不匹配,并且出现了,这是我的最后一次混洗并为所有行打印了它。

例如,我的输出之一是:

3,2,1,4

1、2、4、3

2、1、3、4

2、3、4、1


2、3、4、1

2、3、4、1

2、3、4、1

2、3、4、1

有人可以帮助我理解我的错误吗?

package practice;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;

public class Practice {
  public static void main(String[] args) {
    //Make arraylist for teams
    List < Integer[] > teamMatches = new ArrayList < > ();
    //Array for team numbers
    Integer[] teamNums = new Integer[] {
      1,
      2,
      3,
      4
    };

    for (int i = 0; i < 4; i++) {
      //shuffle array    
      Collections.shuffle(Arrays.asList(teamNums));
      //add array to arraylist
      teamMatches.add(teamNums);
      //print out
      System.out.println(teamMatches.get(i)[0] + ", " + teamMatches.get(i)[1] + ", " +
        teamMatches.get(i)[2] + ", " + teamMatches.get(i)[3]);

    }
    System.out.println("_____________________________");
    //print out entire match array
    for (int n = 0; n < 4; n++) {

      System.out.println(teamMatches.get(n)[0] + ", " + teamMatches.get(n)[1] + ", " +
        teamMatches.get(n)[2] + ", " + teamMatches.get(n)[3]);




    }



  }

1 个答案:

答案 0 :(得分:2)

将teamNums添加到teamMatches时,会将引用(指针)传递到同一数组(相同的内存位置)。因此,在for循环之后打印时,您只会得到最后一次已知的随机播放,因为这就是数组的样子。

您必须为for循环的每次迭代声明一个新的数组变量。 试试:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;

public class Practice {
    public static void main(String[] args) {
        //Make arraylist for teams
        List < Integer[] > teamMatches = new ArrayList < > ();

        for (int i = 0; i < 4; i++) {
            // *create new Array for team numbers
            Integer[] teamNums = new Integer[] {1, 2, 3, 4};

            //shuffle array    
            Collections.shuffle(Arrays.asList(teamNums));

            //add array to arraylist
            teamMatches.add(teamNums);

            //print out
            System.out.println(
                teamMatches.get(i)[0] + ", " 
                + teamMatches.get(i)[1] + ", "
                + teamMatches.get(i)[2] + ", "
                + teamMatches.get(i)[3]
            );
        }
        System.out.println("_____________________________");

        //print out entire match array
        for (int n = 0; n < 4; n++) {    
            System.out.println(
                teamMatches.get(n)[0] + ", "
                + teamMatches.get(n)[1] + ", "
                + teamMatches.get(n)[2] + ", "
                + teamMatches.get(n)[3]); 
        }
    }
}