java – 自动装箱:所以我可以写:整数i = 0;而不是:Integer i = new Integer(0);

前端之家收集整理的这篇文章主要介绍了java – 自动装箱:所以我可以写:整数i = 0;而不是:Integer i = new Integer(0);前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
自动装箱似乎归结于我可以写的事实:
Integer i = 0;

代替:

Integer i = new Integer(0);

因此,编译器可以自动将原语转换为对象.

是这个想法吗?为什么这很重要?

解决方法

你有点简化了一点.

使用集合时,自动装箱也会起作用.如sun的java文档中所述:

Collections can only hold object references,so you have to Box primitive values into the appropriate wrapper class. When you take the object out of the collection,you get the Integer that you put in; if you need an int,you must unBox the Integer using the intValue method. All of this Boxing and unBoxing is a pain,and clutters up your code. The autoBoxing and unBoxing feature automates the process,eliminating the pain and the clutter.

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.

Great overview of Autoboxing

原文链接:https://www.f2er.com/java/122386.html

猜你在找的Java相关文章