简体   繁体   English

“Object [] x”和“Object x []”之间有什么区别吗?

[英]Is there any difference between “Object[] x” and “Object x[]”?

I was updating a legacy code base in Java and I found a line like this: 我正在用Java更新遗留代码库,我找到了这样一行:

Object arg[] = { new Integer(20), new Integer(22) };

That line catched my attention because I am used to this kind of code: 那条线引起了我的注意,因为我习惯了这种代码:

Object[] arg = { new Integer(20), new Integer(22) };

The content of the array isn't important here. 这里的数组内容并不重要。 I'm curious about the brackets next to the variable name versus the brackets next to the class name. 我很好奇变量名旁边的括号与类名旁边的括号。 I tried in Eclipse (with Java 5) and both lines are valid for the compiler. 我在Eclipse(使用Java 5)中尝试过,这两行对编译器都有效。

Is there any difference between those declarations? 这些声明之间有什么区别吗?

Both are legal and both work. 两者都是合法的,都是有效的。 But placing [] before the array's name is recommended. 但建议在数组名称前放置[]。

From Javadocs : 来自Javadocs

You can also place the square brackets after the array's name: 您还可以在数组名称后面放置方括号:

float anArrayOfFloats[]; // this form is discouraged

However, convention discourages this form; 但是,公约不鼓励这种形式; the brackets identify the array type and should appear with the type designation. 括号标识数组类型,并应显示类型名称。

No, they both work. 不,他们都工作。 But watch out: 但请注意:

float anArrayOfFloats[], aSecondVariable;

will declare one array of floats and one float, while: 将声明一个浮点数和一个浮点数,同时:

float[] anArrayOfFloats, aSecondVariable;

will declare two arrays of floats. 将声明两个浮点数组。

There is no difference. 没有区别。 Both are legal. 两者都是合法的。

You can read in Java Language Specification http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html 您可以阅读Java语言规范http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example: []可能在声明开头作为类型的一部分出现,或作为特定变量的声明者的一部分出现,或者两者都出现,如下例所示:

 byte[] rowvector, colvector, matrix[]; 

Another good reason to write Integer[] ints instead of Integer ints[] is because of inheritance relations: Integer[] is subtype of Number[] is subtype of Object[] . 编写Integer[] ints而不是Integer ints[]另一个好理由是因为继承关系: Integer[]Number[]的子类型是Object[]子类型。

In other words, you can put Integers in an Object array, so you can think of the [] as part of the object's type definition -- which is why it makes sense to have it close to the type instead of the object name. 换句话说,您可以将Integers放在Object数组中,这样您就可以将[]视为对象类型定义的一部分 - 这就是为什么让它接近类型而不是对象名称是有意义的。

简答:不。

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

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