Java copy section of array

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


and you create a new array from it:


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


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);

then call like this:

int[] part = partArray(array, 3);


There is a pre-existing method in the java.util.Arrays: newArray = Arrays.copyOfRange(myArray, startindex, endindex). Or you could easily write your own method:

public static array[] copyOfRange(array[] myarray, int from, int to) {
    array[] newarray = new array[to - from];
    for (int i = 0 ; i < to - from ; i++) newarray[i] = myarray[i + from];
    return newarray;

int [] myArray = [1,2,3,4,5];

int [] holder = new int[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

Arrays#copyOfRange does the trick.

Need Your Help

How to make the Win32 APP Background Transparent?


How to make the Win32 APP Background Transparent?

code reuse in front-end rails application

html css ruby-on-rails web user-controls

I'm in the process of development a new website and I noticed the fact that couple of controls appears in different pages. So, a naive approach would be writing those controls every single time, bu...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.