1

I konw that an array is an object in Java. I want to print one array like other objects but this won't work:

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
    }        
}

Can anybody please help me?

1
  • 1
    What are you trying to achieve by inserting reference variable array in line:Object[] obj1={"Nguyen Viet Quan",28,"Doan Thi Ha",array};? Commented Sep 22, 2015 at 4:35

1 Answer 1

3

First your join method only needs one loop to copy obj2 as well as obj1. You could find the maximum length for your loop test. And then copy on each valid index. That might look something like

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;
}

Then you need to save a reference to your joined obj (or print it directly). And because it contains a nested array, you might choose 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)));
}

which outputs (formatted for this post)

[Nguyen Viet Quan, 28, Doan Thi Ha, [1, 2, 3, 4, 5], 
    Nguyen Viet Quan1, 28, Doan Thi Ha1]
Sign up to request clarification or add additional context in comments.

1 Comment

The code for join proposed by OP also works and the only change needed is to print multi-dim array using deepToString.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.