Java:我应该使用浮点数还是浮点数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16528187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:13:25  来源:igfitidea点击:

Java: Should I use float or Float?

javaobjectfloating-pointprimitive-types

提问by Dávid Natingga

My colleague told me that I should use float whenever possible to reduce the object creation and increase the performance. Java silently converts float to Float (this needs some computational power) whenever necessary. So it seems to me that the only need for Float is when one needs to use the object Float very often instead of its primitive.

我的同事告诉我,我应该尽可能使用 float 来减少对象创建并提高性能。Java 会在必要时默默地将 float 转换为 Float(这需要一些计算能力)。所以在我看来,对 Float 的唯一需要是当人们需要经常使用对象 Float 而不是它的原始对象时。

When looking at java.awt.color, it is using the Float, perhaps unnecessarily.

在查看 java.awt.color 时,它正在使用 Float,可能是不必要的。

When would one need to prefer Float over float in Java?

什么时候需要在 Java 中更喜欢 Float 而不是 float?

采纳答案by Woot4Moo

The objectFloatcan be set to null to represent a value that is unknown.
The primitivefloatis guaranteed to have a value.

可以将该对象Float设置为 null 以表示未知的值。
原语float是保证有一个值。

There is some overhead on the autoboxing, but this is negligible. You still must allocate space for the primitive so there is nothing you gain there.

自动装箱有一些开销,但可以忽略不计。您仍然必须为原语分配空间,因此您在那里一无所获。