对象或原始类型
有人可以向我解释一下在 JAVA 中如何使用 Integer、Boolean 等来代替它们的原始类型吗?
我似乎无法理解他们提供的优势。它们似乎在处理空值时造成了不必要的问题。
谢谢!
Can someone explain to me the usage of Integer, Boolean etc in place of their primitive types in JAVA?
I can't seem to grasp the advantages their are providing. They seem to create unnecessary problems of handling null values.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Boolean
、Integer
、Long
、...都是对象。您可以在无法使用原始类型的地方使用它们,例如Map
这样的集合中,null
值Long
作为Number
)示例:
Boolean
,Integer
,Long
, ... are Objects. You can use them in places where you can't use primitive types, e.g.Map
null
valueLong
asNumber
)Examples:
Integer、Boolean 等的基本原理是允许在需要引用类型的上下文中使用原始类型。经典的用例是集合 API,它提供集合、列表、映射、队列等,其中元素类型必须是某种引用类型。
因此我可以这样写:
但以下是一个编译错误:
请注意,原始包装类型的这种用例早于泛型类型和“新”集合 API,并且可以追溯到唯一的集合类型是原始集合类型的时代
Vector
和Hashtable
及其同类的(前通用)形式。The rationale for Integer, Boolean, and so on is to allow primitive types to be used in contexts that require a reference type. The classic use-case is the collection APIs which provide sets, lists, maps, queues and so on where the element type must be some reference type.
Thus I can write:
but the following is a compilation error:
Note that this use-case for the primitive wrapper types predates both generic types and the "new" collections APIs, and goes back to the days where the only collection types were the original (pre-generic) forms of
Vector
andHashtable
, and their ilk.有时您确实需要一个可为空的值,例如,如果您的应用程序存储用户数据,则社会保障号可能未知。在这种情况下,存储 null 而不是 -1 会更干净。
此外,还有一些无法使用基本类型执行的操作,例如将它们存储在映射中或使用多态性(Double 和 Integer 都是 Number 的实例)。
Sometimes you really need a value to be nullable, for instance if your app stores user data, a social security # may be unknown. In that case it's cleaner to store null instead of -1.
Also there are things you can't do with primitive types, like storing them in a map or using polymorphism (Double and Integer both are instances of Number).
基元总是更快。
然而,有时对象确实很有用:
1. 向上。您的函数可以采用 Number(是所有数字对象的父对象:Integer、Float 等)作为参数。
2. 可能存在空值。例如,它在存储在数据库中时使用。对象可以为 null,基元必须具有值。因此,如果数据库中的字段可为空,最好使用原始值的对象版本。
3.如果函数接受对象并且你总是给它一个原语,那么自动装箱(将原语变成对象)就会产生费用。从函数返回也是如此。
4. 对象有某些方法,例如 getHashcode()、toString() 等,这些方法在某些情况下确实很有用。
primitives are always faster.
however there are times, when objects are really useful:
1. upcasting. Your function can take Number(is a parent for all numeric objects: Integer, Float, etc.) for an argument.
2. Possible null value. For example it is used while storing in database. Object can be null, primitives must have value. So if field in db is nullable, it is better to use object version of primitive value.
3. if function takes object and you always give it a primitive there are expenses on autoboxing(turning primitive into object). The same for returning from function.
4. Objects have certain methods, such as getHashcode(), toString() etc., which can be really useful in some cases.