Alex Rivera | Logout

Java copy section of array

Asked 2012-05-02T23:30:51.883
21

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?

Edit
Report

3 Answers

26

See the method Arrays.copyOfRange

answered 2012-05-02T23:31:55.827
24

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);
answered 2012-05-02T23:38:42.207
6
int [] myArray = [1,2,3,4,5];

int [] holder = new int[size];

System.arraycopy(myArray,0,holder,size);

where 0 stands for the index of source array from where copying should start. and

size stands for the number of copy operations. That you can changes according to your need.

copyOfRange of Arrays is there and many other ways by which this can be accomplished

answered 2012-05-02T23:36:44.540

Your Answer