在Java

时间:2015-09-22 04:31:07

标签: java arrays

我知道数组是Java中的一个对象。我想像其他对象一样打印一个数组,但这不会起作用:

public static Object[] join(Object[] obj1,Object[] obj2)
{
    Object[] sum=new Object[obj1.length+obj2.length];
    int i=0;
    for(;i<obj1.length;i++)
    {
        sum[i]=obj1[i];
    }
    for(int j=0;j<obj2.length;j++,i++)        {
        sum[i]=obj2[j];
       // i++;
    }
    return sum;
}

public static void main(String[] args) {
    // TODO code application logic here
    int[] array={1,2,3,4,5};
    Object[] obj1={"Nguyen Viet Q",28,"Doan Thi Ha",array};
    Object[] obj2={"Nguyen Viet Q1",28,"Doan Thi Ha1"};
    join(obj1,obj2);
    for(Object o: join(obj1,obj2))
    {
        System.out.print(o.toString()+" ");// i want to print array object
    }        
}

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

首先,您的join方法只需要一个循环即可复制obj2以及obj1。您可以找到循环测试的最大长度。然后复制每个有效索引。这可能看起来像

public static Object[] join(Object[] obj1, Object[] obj2) {
    Object[] sum = new Object[obj1.length + obj2.length];
    int len = Math.max(obj1.length, obj2.length);
    for (int i = 0; i < len; i++) {
        if (i < obj1.length) {
            sum[i] = obj1[i];
        }
        if (i < obj2.length) {
            sum[i + obj1.length] = obj2[i];
        }
    }
    return sum;
}

然后,您需要保存对已加入的obj(或直接print)的引用。由于它包含嵌套数组,因此您可以选择Arrays.deepToString(Object[])

public static void main(String[] args) {
    int[] array = { 1, 2, 3, 4, 5 };
    Object[] obj1 = { "Nguyen Viet Quan", 28, "Doan Thi Ha", array };
    Object[] obj2 = { "Nguyen Viet Quan1", 28, "Doan Thi Ha1" };
    System.out.println(Arrays.deepToString(join(obj1, obj2)));
}

哪个输出(为此帖格式化)

[Nguyen Viet Quan, 28, Doan Thi Ha, [1, 2, 3, 4, 5], 
    Nguyen Viet Quan1, 28, Doan Thi Ha1]