简体   繁体   English

使用for循环将一个数组分配给另一个数组

[英]Using a for loop to assign an array to another array

I have a project where by I used a sorting algorithm to sort an array but I am at the point where I now need to examine different arrays of different sizes and different values. 我有一个项目,在该项目中,我使用了排序算法对数组进行排序,但现在我需要检查具有不同大小和值的不同数组。 Is there a way I can assign an array to a global array using a for loop eg I have 12 arrays named array1 through to array12 and i need to assign them to a global array called array that is passed in to the sorting algorithm The 12 arrays are passed in to the array from a file 有没有一种方法可以使用for循环将数组分配给全局数组,例如,我有12个名为array1的数组到array12,我需要将它们分配给称为array的全局数组,该数组传递给排序算法12个数组从文件传递到数组

Having variables that look like array1 , array2 , array3 ,..., array12 is a sure sign that you need a single array instead of all these variables. 具有看起来像array1array2array3 ,..., array12是一个确定的信号,即您需要一个数组而不是所有这些变量。 You should put these arrays into an array of arrays, and use array[x] to access them. 您应该将这些数组放入一个数组数组中,并使用array[x]访问它们。

For example, instead of 例如,代替

int[] array1 = new int[] {1, 2, 3};
int[] array2 = new int[] {4, 5, 6};
...
int[] array12 = new int[] {34, 35, 36};

you would write 你会写

int[][] array = new int[][] {
    new int[] {1, 2, 3},
    new int[] {4, 5, 6},
    ...
    new int[] {34, 35, 36}
};

Now instead of writing array5 you would write array[4] (4, not 5, because indexes of Java arrays are zero-based). 现在,您无需编写array5而是编写array[4] (4,而不是5,因为Java数组的索引是从零开始的)。 This indexing can be done with a for loop: 可以使用for循环完成此索引for

int[][] array = new int[][] { ... };
for (int i = 0 ; i != array.length ; i++) {
    callMySort(array[i]);
}

or from a foreach loop: 或从foreach循环中:

int[][] array = new int[][] { ... };
for (int[] sortMe : array) {
    callMySort(sortMe);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM