为什么Java可以接受多个参数但只能返回一个对象?
为什么 java 的定义方法可以接受多个参数作为输入,
但可能只返回单个对象(或 void)?
它是否使该语言更易于实现或使用?
Why was java defined such that methods may take as input multiple parameters,
but may only return a single object (or void)?
Did it make the language somehow easier to implement or use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可能是因为 C 和 C++ 就是这样做的,而 Java 语言的语法与这些语言非常相似(并且可能基于)。
事实上,根据这篇文章, Gosling 首先扩展了 C++ 编译器,因此他遵循大部分相同的语法是有道理的:
Probably because this is the way that C and C++ do it, and the Java language syntax is very similar to (and probably based on) those languages.
In fact, according to this article, Gosling started by extending the C++ compiler, so it makes sense that he would follow much of the same syntax:
也许意图是将多个返回值封装在一个对象中?
Maybe the intention was that multiple return values be encapsulated in an object?
我不确定,但我想 Java 的执行方式就像任何其他基于堆栈的运行时一样。这意味着将项目作为参数传递到方法中,只需在将控制权转移到方法之前将它们推入堆栈即可轻松完成。返回值可能像 C 和 C++ 一样在 VM 中处理 - 返回值始终放置在寄存器中,寄存器本质上是单值。
不过,这并不是一个大问题,因为使用泛型,可以通过返回类似
Tuple
这样的实例,以类型安全的方式处理返回多个值,这不是'在大多数情况下,这并不算太大的负担。I don't know for sure, but I imagine that Java is executed like any other stack-based runtime. Which means that passing items as parameters into a method is done easily by simply pushing them onto the stack before transferring control to the method. Return values are probably handled in the VM like C and C++ do - the return value is always placed in a register, which is by nature single-valued.
It's not a big problem, though, because with generics, returning multiple values can be handled in a type-safe way by returning an instance of something like
Tuple<type1, type2, type3>
, which isn't too great a burden to bear in most cases.我的猜测是约定:这就是主要的面向对象语言所做的事情,所以这就是 Java 所做的事情。然而,官方的论点可能与关于闭包的论点相同——不包括那些会混淆普通任务和非真正需要的任务的标准语法的东西。或者也许他们认为单个方法应该返回一组应该/可以进入对象的相关值。或者也许他们只是没有想到/没有时间(相当标准的开发人员费用)。
在相关说明中,我发现了有关使用闭包模拟多个返回的讨论:
http://weblogs.java.net/blog/brucechapman/存档/2007/11/closures_and_mu.html
My guess would be convention: that's what the major OO languages do/did, so that's what Java did. However, the official argument would probably be the same as the one about closures - don't include things that will cloud up the standard syntax for mundane tasks with not-really-needed tasks. Or maybe they figured that a single method should be returning a set of related values that should/could go into an object. Or maybe they just didn't think of it/have the time (pretty standard developer fare).
On a related note, I found this discussion of using closures to mock multiple returns:
http://weblogs.java.net/blog/brucechapman/archive/2007/11/closures_and_mu.html