[英]How to make a dynamic 2D array and store a shuffled array in it
我創建了一個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]); } }
當您將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]);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.