简体   繁体   English

数组内部的数组-Java

[英]Array inside of an Array - Java

Ok, so I have a 2D array that returns an array. 好的,所以我有一个2D数组返回一个数组。

Object[][] sample = new Object[1][1];
//ok just imagine sample already has an array inside of it

How do I retrive the array within the 2d array? 如何在2d数组中检索数组?

I have tried to create a new array with the value, 我试图用该值创建一个新数组,

object[] = sample[0][0];

but it just creates an error. 但这只会产生错误。

When I print the value of 当我打印的值

sample[0][0]

it returns the value: [[Ljava.lang.Object;@4e25154f 它返回值:[[Ljava.lang.Object; @ 4e25154f

I do not know how to solve this. 我不知道该怎么解决。

sample[0][0] returns the object not int. sample [0] [0]返回的对象不是int。 First you need to downcast it and then retrieve integer value 首先,您需要向下转换它,然后检索整数值

For example :- 例如 :-

CustomObject co = (CustomObject)sample[0][0]; // downcast here

then retrieve the required field from your custom object 然后从您的自定义对象中检索必填字段

sample[0][0] is Object not int[] , sample[0] can be one dimensional array or any Object , note that arrays are also Object in java. sample[0][0]Object而不是int[]sample[0]可以是一维数组或任何Object ,请注意,数组在Java中也是Object

To print multidimensional array you can use Arrays.deepToString(twoDarray) but this does not work if you have stored specifically Object . 要打印多维数组,可以使用Arrays.deepToString(twoDarray)但是如果您专门存储了Object则此方法不起作用。

Moreover, [[Ljava.lang.Object;@4e25154f is the result of default toString representation of the Object stored at sample[0][0] which is I think an array . 此外, [[Ljava.lang.Object;@4e25154f是存储在sample[0][0]处的Object的默认toString表示形式的结果,我认为这是一个数组 To print array you can use Arrays.toString(int[]) . 要打印数组,可以使用Arrays.toString(int[])

I guess this is what you are trying to do, 这就是你想要做的

Object[][] obj = new Object[1][1];
obj[0][0] = new int[]{0,1,0,2};
System.out.println(obj);
//To get int[]
int[] arr= (int[]) obj[0][0];//Need to cast to the int[] specifically
//because it's currently stored as an Object
System.out.println(Arrays.toString(arr));

OUTPUT OUTPUT

[[Ljava.lang.Object;@1db9742
[0, 1, 0, 2]

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

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