何时使用包装类和原始类型 [英] When to use wrapper class and primitive type
问题描述
什么时候我应该选择包装类而不是原始类型?或者在什么情况下我应该在包装器/原始类型之间进行选择?
When I should go for wrapper class over primitive types? Or On what circumstance I should choose between wrapper / Primitive types?
推荐答案
其他人提到某些结构(例如 Collections
).
Others have mentioned that certain constructs such as Collections
require objects and that objects have more overhead than their primitive counterparts (memory & boxing).
另一个考虑是:
将对象初始化为 null
或将 null
参数发送到方法/构造函数以指示状态或函数会很方便.使用原语无法做到这一点.
It can be handy to initialize Objects to null
or send null
parameters into a method/constructor to indicate state or function. This can't be done with primitives.
许多程序员将数字初始化为 0(默认值)或 -1 来表示这一点,但根据具体情况,这可能是不正确的或误导性的.
Many programmers initialize numbers to 0 (default) or -1 to signify this, but depending on the scenario, this may be incorrect or misleading.
当某些东西被错误使用时,这也会为 NullPointerException
设置场景,这比一些任意的错误更适合程序员.
This will also set the scene for a NullPointerException
when something is being used incorrectly, which is much more programmer-friendly than some arbitrary bug down the line.
这篇关于何时使用包装类和原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!