何时使用包装类和基元类型 [英] When to use wrapper class and primitive type

查看:77
本文介绍了何时使用包装类和基元类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候我应该去原始类型的包装类?或者在什么情况下我应该在包装器/原始类型之间进行选择?

When I should go for wrapper class over primitive types? Or On what circumstance i should choose between wrapper / Primitive types?

推荐答案

其他人已经提到过某些结构,例如集合需要对象和那些对象比原始对象(内存和拳击)有更多的开销。

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 的场景比一些任意的bug更加程序员友好。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆