Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java copy section of array [duplicate]

Tags:

Is there a method that will copy a section of an array(not arraylist) and make a new array from it?

Example: [1,2,3,4,5] 

and you create a new array from it:

[1,2,3] 

Are there any one line/methods that will do this?

like image 904
user1102901 Avatar asked May 02 '12 23:05

user1102901


People also ask

Which is the best approach to copying elements from part of one array A to another array B?

b = Arrays. copyOf(a, a. length); Which allocates a new array, copies over the elements of a , and returns the new array.


2 Answers

See the method Arrays.copyOfRange

like image 73
Jeffrey Avatar answered Nov 02 '22 07:11

Jeffrey


Here's a java 1.4 compatible 1.5-liner:

int[] array = { 1, 2, 3, 4, 5 }; int size = 3;  int[] part = new int[size]; System.arraycopy(array, 0, part, 0, size); 

You could do this in one line, but you wouldn't have a reference to the result.

To make a one-liner, you could refactor this into a method:

private static int[] partArray(int[] array, int size) {     int[] part = new int[size];     System.arraycopy(array, 0, part, 0, size);     return part; } 

then call like this:

int[] part = partArray(array, 3); 
like image 32
Bohemian Avatar answered Nov 02 '22 05:11

Bohemian