Boolean b = true ;
它会奏效我现在有一个保存值为“true”的对象.
Boolean b = new Boolean( true ) ;
此外,我可以用类似的方式实现自定义类吗?如果是这样的话呢?
所以我可以做这样的事情:
Foobar foobar = "Test" ;
因此有我自己的包装类.
谢谢
解决方法
前者被称为autoboxing,并在Java v1.5中引入自动包装,其包装对象中的原语.
使用泛型和/或集合时,可以清楚地看到自动装箱的好处:
在“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.
原文地址:https://www.jb51.cc/java/125662.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。