开发者

Put an array of Objects in nodes of another array of Objects [JAVA]

开发者 https://www.devze.com 2022-12-29 16:33 出处:网络
public class hello { public static void main(String[] args) { Object[] newarray = new Object[1]; Object[] obj = new Object[2];
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 stor开发者_如何学编程ed in obj[0] and obj[1]; obj is in newarray[0]. what should I do?

Is this possible?

Thanks


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];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号