Java数组类型声明

时间:2014-12-22 06:21:27

标签: java arrays types declaration

对于以下代码行:

int x [ ] = new int [5]

为什么需要第二个int?第二种类型声明与第一种不完全相同吗?

3 个答案:

答案 0 :(得分:3)

在这个特定情况下,它可能看起来冗长冗余,但由于我们正在处理OO语言,因此很可能(并且很有用)遇到如下声明:

Shape shape = new Triangle(); //where Triangle implements Shape interface

同样的原因在于,Array可以是通用类型,包含不同类型的项,或不同类型的数组(扩展相同类型)。例如:

Number[] tmpNumbersArray = new Integer[10]; // 

答案 1 :(得分:1)

不,原因。

Number [] numbers = new Float[5];

答案 2 :(得分:0)

如果在编译时有值,可以试试这个:

int[] x = {34, 45, 78};

另见:

数据类型声明

int[] a,b = new int[3]; //multiple arrays declared

声明变量

int a[], b;//multiple declaration, but not all are arrays
a = new int[3];//later you can define the array size