为什么Java中布尔对象有一个公共构造函数?
Java 中构造函数 new Boolean(boolean value)
的文档指出:
注意:很少适合使用此构造函数。除非需要新实例,否则静态工厂
valueOf(boolean)
通常是更好的选择。它可能会产生明显更好的空间和时间性能。
如果是这样,为什么这个构造函数是公开的并且没有被弃用?是否有充分的理由使用此构造函数而不是 Boolean.valueOf()
?
Documentation for the constructor new Boolean(boolean value)
in Java states:
Note: It is rarely appropriate to use this constructor. Unless a new instance is required, the static factory
valueOf(boolean)
is generally a better choice. It is likely to yield significantly better space and time performance.
If so, why is this constructor public and not deprecated? Is there ever a good reason to use this constructor instead of Boolean.valueOf()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
valueOf()
仅在 Java 1.4 中添加,因此构造函数的存在似乎是为了向后兼容。这张票解释了不弃用构造函数的原因:
我无法想象使用布尔构造函数是做一些有用的事情的最佳方式的现实场景。
valueOf()
only got added in Java 1.4, so it would appear that the constructors exist for backwards compatibility.This ticket explains the reasons for not deprecating the constructors:
I can't think of a realistic scenario where using
Boolean
constructors would be the best way to do something useful.通常,您需要直接使用
valueOf(boolean)
甚至Boolean.TRUE
/Boolean.FALSE
常量。但请考虑一个场景,您希望使用私有布尔变量作为同步线程的监视器。在那里,您需要确保使用自己的实例并完全控制它。
Usually, you will want to use
valueOf(boolean)
or even theBoolean.TRUE
/Boolean.FALSE
constants directly.But think of a scenario where you want to use a private
Boolean
variable as a monitor for synchronizing threads. There you will need to make sure you use your own instance and have full control of it.另一个不一定是好的理由可能是简单地使其与其他本机包装器保持一致。
Another, not necessarily good reason would probably be to simply keep it consistent with the other native wrappers.
从 Java 9 开始,
Boolean(boolean)
构造函数已被弃用;请参阅 javadoc。对于那些关心历史的人来说,有一个长期存在的 bug要求弃用构造函数。它是在 JEP 277 中正式提出的,同时还有许多其他弃用。
As of Java 9, the
Boolean(boolean)
constructor has been deprecated; see javadoc.For those who care about the history, there was a longstanding bug that called for the deprecation of the constructor. It was formally proposed in JEP 277 along with a number of other deprecations.
它没有被弃用的原因是 Java 保持了对 1.0 版本的向后兼容性,
我想不出使用构造函数的好理由。
The reason it hasn't been deprecated is that Java maintains backwards compatibility to version 1.0
I can't think of a good reason to use the constructor.