Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copying portion of object array in Java

Tags:

java

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?

like image 204
Liondancer Avatar asked Feb 19 '26 14:02

Liondancer


1 Answers

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)
like image 103
Rod_Algonquin Avatar answered Feb 21 '26 03:02

Rod_Algonquin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!