Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you set one array's values to another array's values in Java?

Tags:

java

arrays

Lets say you had two arrays:

    int[] a = {2, 3, 4};
    int[] b = {4, 5, 6};

How would you set array a to array b and keep them different different objects? Like I thought of doing this:

    a = b; 

But that doesn't work since it just makes "a" reference array b. So, is the only way to set two arrays equal, while keeping them separate objects, to loop through every element of one array and set it to the other?

And what about ArrayList? How would you set one ArrayList equal to another when you have objects in them?

like image 267
CowZow Avatar asked Oct 24 '11 21:10

CowZow


People also ask

Can you set one array equal to another Java?

As mentioned above, arrays in Java can be set equal to another array using several ways. Here are a few ways: Create an array with the same length as the previous and copy every element. Using the System.

How do you assign a sorted array to another array in Java?

You can sort within the array using Arrays. sort() method, or if you want to sort in a different array, you can take following steps: Copy the array to new array. Sort the new array and then sort.


1 Answers

You may want to use clone:

a = b.clone();

or use arraycopy(Object source, int sourcePosition, Object destination, int destinationPosition, int numberOfElements)

System.arraycopy(b, 0, a, 0, b.length());
like image 59
Eng.Fouad Avatar answered Sep 30 '22 11:09

Eng.Fouad