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?
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With