If I have an object array in Java Car[] a = {0,1,2,3,4,5,6,7}. How would I make a copy of this array from index 2 to 7?
I thought about making a for loop
Car[] b = new Car[a.length - 2];
for (int i = 2; i < a.length; i++) {
b[i - 2] = a[i];
}
Is there another way by using some of Java's built in Library? If there is, would it be more or less efficient than the for loop I proposed?
You can use the copyOfRange of the Arrays class to copy certain ranges.
sample:
Arrays.copyOfRange(b, 2, 7);
Method implementation
copyOfRange(T[] original,
int from,
int to)
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