加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java Boolean包装器类如何实例化?

发布时间:2020-12-14 16:21:11 所属栏目:Java 来源:网络整理
导读:在 java中,我可以这样编写代码 Boolean b = true ; 它会奏效我现在有一个保存值为“true”的对象. 这是如何工作的?为什么我不能通过构造函数传递值?像这样: Boolean b = new Boolean( true ) ; 此外,我可以用类似的方式实现自定义类吗?如果是这样的话呢
在 java中,我可以这样编写代码
Boolean b = true ;

它会奏效我现在有一个保存值为“true”的对象.

这是如何工作的?为什么我不能通过构造函数传递值?像这样:

Boolean b = new Boolean( true ) ;

此外,我可以用类似的方式实现自定义类吗?如果是这样的话呢?

所以我可以做这样的事情:

Foobar foobar = "Test" ;

因此有我自己的包装类.

谢谢

解决方法

不,你不能做后者.

前者被称为autoboxing,并在Java v1.5中引入自动包装,其包装对象中的原语.

使用泛型和/或集合时,可以清楚地看到自动装箱的好处:

从文章:J2SE 5.0 in a Nutshell

在“Autoboxing and Auto-Unboxing of Primitive Types”样本中,我们有:

之前(添加了自动装箱)

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0,new Integer(42)); 
int total = (list.get(0)).intValue();

ArrayList<Integer> list = new ArrayList<Integer>();
 list.add(0,42);
 int total = list.get(0);

如你所见,代码更清楚.

请记住文档上的最后一个注意事项:

So when should you use autoboxing and unboxing? Use them only when there is an “impedance mismatch” between reference types and primitives,for example,when you have to put numerical values into a collection. It is not appropriate to use autoboxing and unboxing for scientific computing,or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types,but they do not eliminate it.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读