Reputation: 69
I am trying to combine two arrays into one big array. But I don't understand why it wont work.
Here's my code:
public class TestaCombine {
private int[] arrayX = new int[20];
private int[] arrayY = new int[6];
private int[] ratings;
public void getRanks(){
arrayX[0] = 3;
arrayX[1] = 4;
arrayX[2] = 2;
arrayX[3] = 6;
arrayX[4] = 2;
arrayX[5] = 5;
arrayY[0] = 9;
arrayY[1] = 7;
arrayY[2] = 5;
arrayY[3] = 10;
arrayY[4] = 6;
arrayY[5] = 8;
}
public void combine(){
ratings = new int[arrayX.length + arrayY.length];
System.arraycopy(arrayX, 0, ratings, 0, arrayX.length);
System.arraycopy(arrayY, 0, ratings, arrayX.length, arrayY.length);
Arrays.sort(ratings);
}
public void print(){
System.out.println(Arrays.toString(ratings));
}
public static void main(String[] args){
TestaCombine tc = new TestaCombine();
tc.getRanks();
tc.combine();
tc.print();
}
The output I am getting looks like this: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 3, 4, 5, 5, 6, 6, 7, 8, 9, 10]
Don't understand where all the 0s comes from.
Upvotes: 0
Views: 151
Reputation: 2083
It is because you have created one array with size of 20 and you only initialized 6 values within it, the rest of values where initialized during array initialization and they were all populated to 0's. When you combined array of size 20 and array of size 6 you received array of size 26 where 14 values are 0's
I would also like to recommend you apache commons libraries which contains nice set of tools for managing different collections.
Upvotes: 0
Reputation: 1168
You're combining an array of size 6 with an array of size 20. The resulting array therefore has a size of 26.
But you've only specified 12 values, so the rest are filled in with values of 0. As you're sorting the collections, this also puts all the 0s at the start of the array.
Upvotes: 0
Reputation: 96018
Note that the size of arrayX
is 20. By default, int
s have 0 value in Java. See the JLS - 4.12.5. Initial Values of Variables:
For type int, the default value is zero, that is, 0.
So when you do:
System.arraycopy(arrayX, 0, ratings, 0, arrayX.length);
It copies the zeros as well.
Upvotes: 3