1

I have some questions regarding arrays in java:

How many objects are created in the following expressions?

(a) new int[0] : There is one object created, an array of size 0.???

(b) new int[2][2] : There is one object created, an array with 2 rows and columns.???

(c) new int[2][] : There is no object created???

I was wondering if my solutions next to the expressions are correct. If not, hopefuly you can help and give me some explanation about them. I don't really get what im supposed to do.

Thanks in advance!

4

2 回答 2

4

以下是 Java 规范的摘录:

在 Java 编程语言中,数组是对象(第 4.3.1 节),是动态创建的,并且可以分配给 Object 类型的变量(第 4.3.2 节)。Object 类的所有方法都可以在数组上调用。

这意味着每个数组都是一个自己的对象,这使您的答案a)正确。

b)创建 3 个对象:首先创建 1 个数组,然后创建两个数组,每个数组包含 2int秒。我不会计算int-entries,因为它们是 Java 中的原始类型。

c)创建了 1 个对象:1 个包含两个空条目的数组。

于 2012-12-22T10:59:53.767 回答
3

新整数[0]

是的,这是一个空数组,创建了一个对象。

    int[] emptyArray = new int[0];
    System.out.println(emptyArray.length); // Outputs 0

新整数[2][2]

是的,这创建了 2 行和列的数组,创建了 3 个对象。

    int[][] bar = new int[2][2];
    System.out.println(bar.getClass()); // Outputs class [[I
    int[] bar1 = bar[0];
    System.out.println(bar1.getClass());  // Outputs class [I
    int[] bar2 = bar[1];
    System.out.println(bar2.getClass());  // Outputs class [I

新 int[2][]

Java 支持锯齿状数组。这意味着当你创建int[2][]这意味着你有一个不同大小的数组int[]。此处仅创建 1 个对象。

    int[][] foo = new int[2][];
    System.out.println(foo[0]);  // Outputs null
    System.out.println(foo[1]);  // Outputs null
    foo[0] = new int[10];
    foo[1] = new int[5];
于 2012-12-22T10:57:12.343 回答