简体   繁体   English

将两个数组合并为一个

[英]Combine two arrays into one

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] 我得到的输出看起来像这样:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,3,4,5,5, 6,6,7,8,9,10]

Don't understand where all the 0s comes from. 不明白所有0的来源。

Note that the size of arrayX is 20. By default, int s have 0 value in Java. 请注意, arrayX的大小为20。默认情况下, int在Java中的值为0。 See the JLS - 4.12.5. 参见JLS -4.12.5。 Initial Values of Variables : 变量的初始值

For type int, the default value is zero, that is, 0. 对于int类型,默认值为零,即0。

So when you do: 因此,当您这样做时:

System.arraycopy(arrayX, 0, ratings, 0,  arrayX.length);

It copies the zeros as well. 它也复制零。

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. 这是因为您创建了一个大小为20的数组,并且只在其中初始化了6个值,其余的值在数组初始化期间进行了初始化,并且它们都填充为0。 When you combined array of size 20 and array of size 6 you received array of size 26 where 14 values are 0's 当您将大小为20的数组和大小为6的数组组合在一起时,会收到大小为26的数组,其中14个值为0

I would also like to recommend you apache commons libraries which contains nice set of tools for managing different collections. 我还建议您使用apache commons库,该库包含一组用于管理不同集合的好工具。

You're combining an array of size 6 with an array of size 20. The resulting array therefore has a size of 26. 您正在将大小为6的数组与大小为20的数组组合在一起。因此,所得数组的大小为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. 但是您只指定了12个值,因此其余的都填充为0。在对集合进行排序时,这也将所有0置于数组的开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM