“Object[] x”和“Object[] x”之间有什么区别吗?和“对象x[]”?
我正在更新 Java 中的遗留代码库,发现了这样一行:
Object arg[] = { new Integer(20), new Integer(22) };
该行引起了我的注意,因为我习惯了这种代码:
Object[] arg = { new Integer(20), new Integer(22) };
数组的内容在这里并不重要。我很好奇变量名旁边的括号与类名旁边的括号。我在 Eclipse(使用 Java 5)中尝试过,这两行对于编译器都有效。
这些声明之间有什么区别吗?
I was updating a legacy code base in Java and I found a line like this:
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.
Is there any difference between those declarations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
两者都是合法且有效的。但建议将 [] 放在数组名称之前。
来自 Javadocs:
Both are legal and both work. But placing [] before the array's name is recommended.
From Javadocs:
不,他们都工作。但请注意:
将声明一个浮点数数组和一个浮点数,而:
将声明两个 浮点数数组。
No, they both work. But watch out:
will declare one array of floats and one float, while:
will declare two arrays of floats.
没有什么区别。两者都是合法的。
您可以阅读Java语言规范 http://java .sun.com/docs/books/jls/second_edition/html/arrays.doc.html
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
编写
Integer[] ints
而不是Integer ints[]
的另一个好理由是继承关系:Integer[]
是的子类型>Number[]
是Object[]
的子类型。换句话说,您可以将
Integers
放入Object
数组中,因此您可以将[]
视为对象类型定义的一部分 - - 这就是为什么让它接近类型而不是对象名称是有意义的。Another good reason to write
Integer[] ints
instead ofInteger ints[]
is because of inheritance relations:Integer[]
is subtype ofNumber[]
is subtype ofObject[]
.In other words, you can put
Integers
in anObject
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.简短回答:不。
Short answer: No.