简体   繁体   English

如何在 java 中将一个数组中的值分配给另一个数组

[英]How to assign values in one array to another in java

I have two arrays and I am trying to assign the values of one array, ie arrayOne[0] should be equal to the corresponding index in arrayTwo[0].我有两个 arrays 并且我正在尝试分配一个数组的值,即 arrayOne[0] 应该等于 arrayTwo[0] 中的相应索引。 I am trying to do this using a forloop so that it loops through the the index of one array assigning the values sequentially.我正在尝试使用 forloop 执行此操作,以便它循环遍历一个数组的索引,按顺序分配值。 so far I have: for (int a =0; a< arrayOne.length; ++) { // this sets the an int that loops through the value of the arrays(both arrayOne and arrayTwo are the same length) I am lost however after this how to create the for loop which assigns index 0 = 0 and then incrementally step through this.到目前为止我有: for (int a =0; a< arrayOne.length; ++) { // 这设置了一个循环遍历数组值的 int(arrayOne 和 arrayTwo 的长度相同)我迷路了但是在此之后如何创建分配索引 0 = 0 的 for 循环,然后逐步执行此操作。

I know this is a very basic question but I am, as my name suggests, struggling to learn coding.我知道这是一个非常基本的问题,但正如我的名字所暗示的那样,我正在努力学习编码。

I am lost however after this how to create the for loop which assigns index 0 = 0 and then incrementally step through this.但是,在此之后,我迷失了如何创建分配索引 0 = 0 的 for 循环,然后逐步执行此操作。

There are many ways to copy arrays.复制 arrays 的方法有很多。 But since you specifically asked for a for loop solution, just create a new array of the same size and use a for loop as shown to index them.但是由于您特别要求使用 for 循环解决方案,因此只需创建一个相同大小的新数组并使用所示的for loop来索引它们。

int [] a = {1,2,3,4,5,6,7};
int [] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
     b[i] = a[i]; // this copies element a[i] to b[i] where i is the index.
}

System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));

Prints印刷

[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]

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

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