How do I copy an array in Java?

Asked 1 years ago, Updated 1 years ago, 120 views

There's a value [1,2,3,4,5] in the array A, and even if you copy the value of A to B and change A to [6,7,8,9,10], B wants to remain as [1,2,3,4,5]

for(int i=0; i<5; i++){
   B[i]=A[i]
}

I did it like this. Not the way I want to. How shall I do it?

java array copy

2022-09-22 08:44

1 Answers

System.arraycopy() method is simple.

int[] src  = new int[]{1,2,3,4,5};
int[] dest = new int[5];

System.arraycopy( src, 0, dest, 0, src.length );

You can do it like this.


2022-09-22 08:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.