Java array copy section

Is there a way that will copy an array section (not an arraylist) and output a new array from it?

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

and you create a new array from it:

 [1,2,3] 

Is there one line / methods that will do this?

+12
java arrays copy
source share
7 answers

Here is compatible with java 1.4 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 can do this in one line, but you will not have a link to the result.

To do a one-line, you can reorganize 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); 
+17
source share
+21
source share

There is an existing method in java.util.Arrays : newArray = Arrays.copyOfRange(myArray, startindex, endindex) . Or you can 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; } 
+7
source share
 int [] myArray = [1,2,3,4,5]; int [] holder = new int[size]; System.arraycopy(myArray,0,holder,size); 

where 0 denotes the index of the source array from which copying should begin. and

size means the number of copy operations. What you can change to suit your needs.

copyOfRange arrays there are many other ways in which this can be achieved.

+5
source share

Arrays # copyOfRange does the trick.

+4
source share

As others have pointed out, you can use the Arrays.copyOfRange method. Example:

 String[] main = {"one", "two", "three", "four", "five"}; int from = 2; int to = 4; String[] part = Arrays.copyOfRange(main, from, to); 

Now the part will be: {"two", "three", "four" }

+2
source share
 import java.util.Arrays; /* in case you want users to enter input you can use this */ public class Solution { public static void main(String[] args) throws Exception { //write your code here int [] smallerOne = new int [10]; int [] smallerTwo = new int [10]; int [] numbers = new int [20]; BufferedReader red = new BufferedReader(new InputStreamReader(System.in)); for (int i = 0; i < numbers.length; i++){ int number = Integer.parseInt(red.readLine()); numbers[i] = number; } smallerOne = Arrays.copyOf(numbers, 10); smallerTwo = Arrays.copyOfRange(numbers, 10,20); for (int i=0;i<10;i++) System.out.println(smallerTwo[i]); } } 
0
source share

All Articles