J2SE 5.0的新特性---Autoboxing

j2se

Autoboxing
As any Java programmer knows, you can’t put an int (or other primitive value) into a collection. Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int). 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.

The following example illustrates autoboxing and unboxing, along with generics and the for-each loop. In a mere ten lines of code, it computes and prints an alphabetized frequency table of the words appearing on the command line.

import java.util.*;// Prints a frequency table of the words on the command linepublic class Frequency { public static void main(String[] args) { Map<String, Integer> m = new TreeMap<String, Integer>(); for (String word : args) { Integer freq = m.get(word); m.put(word, (freq == null ? 1 : freq + 1)); } System.out.println(m); }}java Frequency if it is to be it is up to me to do the watusi{be=1, do=1, if=1, is=2, it=2, me=1, the=1, to=3, up=1, watusi=1}

The program first declares a map from String to Integer, associating the number of times a word occurs on the command line with the word. Then it iterates over each word on the command line. For each word, it looks up the word in the map. Then it puts a revised entry for the word into the map. The line that does this (highlighted in green) contains both autoboxing and unboxing. To compute the new value to associate with the word, first it looks at the current value (freq). If it is null, this is the first occurrence of the word, so it puts 1 into the map. Otherwise, it adds 1 to the number of prior occurrences and puts that value into the map. But of course you cannot put an int into a map, nor can you add one to an Integer. What is really happening is this: In order to add 1 to freq, it is automatically unboxed, resulting in an expression of type int. Since both of the alternative expressions in the conditional expression are of type int, so too is the conditional expression itself. In order to put this int value into the map, it is automatically boxed into an Integer.

The result of all this magic is that you can largely ignore the distinction between int and Integer, with a few caveats. An Integer expression can have a null value. If your program tries to autounbox null, it will throw a NullPointerException. The == operator performs reference identity comparisons on Integer expressions and value equality comparisons on int expressions. Finally, there are performance costs associated with boxing and unboxing, even if it is done automatically.

Here is another sample program featuring autoboxing and unboxing. It is a static factory that takes an int array and returns a List of Integer backed by the array. In a mere ten lines of code this method provides the full richness of the List interface atop an int array. All changes to the list write through to the array and vice-versa. The lines that use autoboxing or unboxing are highlighted in green:

// List adapter for primitive int arraypublic static List<Integer> asList(final int[] a) { return new AbstractList<Integer>() { public Integer get(int i) { return a[i]; } // Throws NullPointerException if val == null public Integer set(int i, Integer val) { Integer oldVal = a[i]; a[i] = val; return oldVal; } public int size() { return a.length; } };}

The performance of the resulting list is likely to be poor, as it boxes or unboxes on every get or set operation. It is plenty fast enough for occasional use, but it would be folly to use it in a performance critical inner loop.

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.

时间: 2024-10-30 13:14:16

J2SE 5.0的新特性---Autoboxing的相关文章

在Eclipse 3.1中体验J2SE 5.0的新特性: 第一部分 :枚举类型

J2SE 5.0 (Tiger)的发布是Java语言发展史上的一个重要的里程碑, 是迄今为止在 Java 编程方面所取得的最大进步. J2SE 5.0提供了很多令人激动的特性.这些特性包括范型(generics)的支持, 枚举类型 (enumeration)的支持, 元数据(metadata)的支持, 自动拆箱(unboxing)/装箱 (autoboxing), 可变个数参数(varargs), 静态导入(static imports), 以及新的线程架 构(Thread framework)

在Eclipse 3.1中体验J2SE 5.0的新特性: 第三部分 :范型

J2SE 5.0 (Tiger)的发布是Java语言发展史上的一个重要的里程碑, 是迄今为止在 Java 编程方面所取得的最大进步. J2SE 5.0提供了很多令人激动的特性.这些特性包括范型(generics)的支持, 枚举类 型(enumeration)的支持, 元数据(metadata)的支持, 自动拆箱(unboxing)/装箱 (autoboxing), 可变个数参数(varargs), 静态导入(static imports), 以及新的线程架 构(Thread framework)

在Eclipse 3.1中体验J2SE 5.0的新特性 第二部分 :注释类型

J2SE 5.0 (Tiger)的发布是Java语言发展史上的一个重要的里程碑, 是迄今为止在 Java 编程方面所取得的最大进步. J2SE 5.0提供了很多令人激动的特性.这些特性包括范型(generics)的支持, 枚举类 型(enumeration)的支持, 元数据(metadata)的支持, 自动拆箱(unboxing)/装箱 (autoboxing), 可变个数参数(varargs), 静态导入(static imports), 以及新的线程架 构(Thread framework)

J2SE 5.0 语言新特性

j2se  JavaTM Language Features For more information see New Language Features. Generics This long-awaited enhancement to the type system allows a type or method to operate on objects of various types while providing compile-time type safety. It adds

在低版本的vc中使用vc 10.0的新特性

/*! 在低版本的vc中使用vc 10.0的新特性 created by : andrew.wu (erpingwu@gmail.com) */ vc 10.0提供了一些新的特性,最引人注目的莫过于lambda, 但vs2010 beta内存占用之多也不得不让人心生退让. 高手 7cat 指出 "vc ide 只是一个壳" 那么如果利用 vc 10.0 编译器的新功能? 以vc9为例, 注意 Tools->Projects and Solutions->VC++ Direc

Spring 2.0的新特性点评

Spring2.0的发布恐怕算得上2006年Java社区的一件大事了.在Spring2.0发布附带的文档里面对2.0新特性做了概要的介绍,2.0的新特性是自然是我们最关注的方面: 一.Spring的XML配置引入XML Schema语法简化配置 在Spring1.x系列中,bean的配置文件使用DTD,没有namespace的分隔.2.0的一个非常大的改进是引入了XML Schema的namespace,因而可以将bean的配置文件做大幅度的简化.这些简化包括了对bean属性的各种简化,AOP配

《Ext JS实战》——1.4 Ext JS 3.0的新特性

1.4 Ext JS 3.0的新特性 Ext JS 2.0中引入的一些变化是颠覆性的,这就导致从级到2.0相当困难.这主要是因为这一版引入了一个更加现代的布局管理器以及一个崭新的.健壮的组件层次,许多Ext JS 1.x的代码都会因此而崩溃.值得庆幸的是,由于Ext JS 2.0的良好的工艺设计,从Ext JS 2.0到3.0的移植就非常容易了.尽管Ext JS 3.0新增的内容并不怎么神奇,不过最新的版本还是可圈可点的,有些新增的特性还是值得讨论的. 1.4.1 Ext JS通过Direct完

[测验]C# 3.0新特性也已经基本定稿了,各种资料层出不穷,但大家对C# 2.0的新特性有多少了解呢?测验一下。

问题描述 入门题:以下哪个特性不是C#2.0的新特性:A.::命名空间别名限定符B.运算符重载C.空值类型D.匿名方法E.迭代器语法记忆题:以下哪个关键字不是C#2.0新增的:A.yeildB.globalC.fromD.fixedE.where提高题:以下关于匿名方法的说法,哪个是错的?A.匿名方法没有方法名B.匿名方法以委托的形式存在C.匿名方法方法参数类型是自动推断的D.匿名方法返回值类型是自动推断的E.匿名方法不能直接赋值给没有方法签名的Delegate类型对象.终极题:嗯嗯,既然是终极

C#7.0中新特性汇总_C#教程

以下将是 C# 7.0 中所有计划的语言特性的描述.随着 Visual Studio "15" Preview 4 版本的发布,这些特性中的大部分将活跃起来.现在是时候来展示这些特性,你也告诉借此告诉我们你的想法! C#7.0 增加了许多新功能,并专注于数据消费,简化代码和性能的改善.或许最大的特性就是元祖和模式匹配,元祖可以很容易地拥有多个返回结果,而模型匹配可以根据数据的"形"的不同来简化代码.我们希望,将它们结合起来,从而使你的代码更加简洁高效,也可以使你更加