Reputation: 16469
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?
Upvotes: 2
Views: 843
Reputation: 2365
CopiesofRange() of the Arrays seems to be a recommended method to perform a copy of a specified range into another array.
Signature
public static <T> T[] copyOfRange(T[] original,
int from,
int to)
T is generic and can be replaced by any class or primary type of variables.
Upvotes: 1
Reputation: 201439
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?
Use one of the Arrays.copyOfRange()
methods like Arrays.copyOfRange(T[], int, int)
,
Car[] b = Arrays.copyOfRange(a, 2, 7);
From the Javadoc,
Copies the specified range of the specified array into a new array.
It is also possible to use System.arraycopy(Object,int,Object,int,int)
,
Car[] b = new Car[a.length - 2];
System.arraycopy(a, 2, b, 0, b.length);
And its Javadoc,
Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.
Upvotes: 2
Reputation: 41200
Arrays#copyOfRange
- Copies the specified range of the specified array into a new array.
java.util.Arrays.copyOfRange(copyFrom, startindex, endIndex);
Arrays#copyOfRange
method internally use System#arraycopy
. Source for reference
AND alternatively you can use System utility it also.
System#arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
-
Upvotes: 4
Reputation: 5224
You can use
Car[] splitArray = Arrays.copyOfRange(a, starting_index, end_index);
Upvotes: 3
Reputation: 17422
System arraycopy:
System.arraycopy(a, 2, b, 0, 5);
where b is your destination, starting from index 2, taking 5 (up to position 7)
Upvotes: 4
Reputation: 4296
You can use the Arrays
class:
b = Arrays.copyOfRange(a, 2, 7);
Upvotes: 4
Reputation: 26198
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)
Upvotes: 5