Reputation: 39
How do I partition an array into four sub arrays in Java?
Upvotes: 2
Views: 15043
Reputation: 101
See my answer here:
Split an array in multiple arrays with a specific maximum size
What's the maximum size you have to evaluate by dividing the array length by the number of sub arryas (beware of float results, it must be an Integer).
Upvotes: 1
Reputation: 371
In addition to what was already said, you could use one of the Arrays.copyOfRange(...) methods available in class java.util.Arrays
.
Upvotes: 1
Reputation: 495
Ordinary partitioning... I would use one of the two ways below:
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);
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.
Upvotes: 1
Reputation: 12257
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);
Upvotes: 11