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.