tags:

views:

172

answers:

3

How do I partition an array into four sub arrays in Java?

+6  A: 

Create 2 Array of the length you want to have it.

And use

System.arraycopy(src, srcPos, dest, destPos, length)

to copy the values from the original to the two new target arraies.

Example:

    int[] original = new int [13];
    int[] a = new int[3];
    int[] b = new int[10];

    System.arraycopy(original, 0, a, 0, 3);
    System.arraycopy(original, 3, b, 0, 10);
Markus Lausberg
A: 

Ordinary partitioning... I would use one of the two ways below:

  1. If you need to move groups of items into separate arrays, for example items 0 to 10 to array 1, 11 to 20 to array 2 etc., I would create four arrays and use System.arraycopy() static method:

    System.arraycopy(sourceArray, sourceStart, destArray, destStart, length);
    
  2. If you must check, where a particular item should go, create four arrays, four index counter variables and make a loop through the elements of the original array. Test the condition and add it to one of the four arrays, incrementing the appropriate index counter.

Zyx
A: 

In addition to what was already said, you could use one of the Arrays.copyOfRange(...) methods available in class java.util.Arrays.

Tobias Müller