简体   繁体   中英

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]. I am trying to do this using a forloop so that it loops through the the index of one array assigning the values sequentially. 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.

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.

There are many ways to copy 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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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