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
Java: Should I use float or Float?
提问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 objectFloat
can be set to null to represent a value that is unknown.
The primitivefloat
is 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.
自动装箱有一些开销,但可以忽略不计。您仍然必须为原语分配空间,因此您在那里一无所获。