java copy array

 

13down voteaccepted

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);
posted @ 2018-04-16 15:46  kakaisgood  阅读(188)  评论(0编辑  收藏  举报