tags:

views:

57

answers:

1
public class hello
{
    public static void main(String[] args)
    {
        Object[] newarray = new Object[1];
        Object[] obj = new Object[2];

        obj[0] = "Number1"; //string value
        obj[1] = "Number2"; //string value

        newarray[0] = obj; //this works

        Object[] tmp_obj = new Object[2];

        tmp_obj = newarray[0]; //obviously does not work
        System.out.println(tmp_obj[0]); //nope
        System.out.println(tmp_obj[1]); //nope
    }
}

So, now if I want to access the values "Number1" and "Number2" which are stored in obj[0] and obj[1]; obj is in newarray[0]. what should I do?

Is this possible?

Thanks

+3  A: 

You just need a cast:

tmp_obj = (Object[]) newarray[0];

That says, "I know that newarray[0] isn't just any old Object - it's an Object[]" (Modulo array variance; let's leave that out here.)

Note that the new Object[2] from the previous line will be instant garbage - the code would be better as:

Object[] tmp_obj = (Object[]) newarray[0];
Jon Skeet
I thought it implicitly casts.
jonathanasdf
@jonathanasdf: An implicit cast from `Object` to `Object[]`? Absolutely not.
Jon Skeet
ahh, I see now.
jonathanasdf
It works!!!!!!! Btw, Mr Skeet, I am big fan of urs!! :)
zengr
@zengr: I'm glad it works for you - do you understand *why* it works, or do you want some more detail?
Jon Skeet
Yup, I got it! Object and Object[] are not the same. So you need to cast the values of the newarray[0] to another object array (tmp_obj).
zengr
why not just allocate and initialize an Object[][] and avoid the casts?
mdma
@mdma was a "concept clarification question" rather an actual implementation question. I can also say, why not use Ruby and avoid the data type problem :P
zengr