Java-基本类型优先于装箱基本类型
Integer year = 2013; // auto-boxing
这里将值为2013的int类型赋值给引用类型为Integer的引用变量year。
实际上该语句等价于:
Integer year = Integer.valueOf(2013);
?通过调用Integer的静态方法valueOf将基本类型转换成Integer引用类型。
?
下面是自动拆箱的一个例子:
Integer year = 2013;int iyear = year;
?这里将int的包装类Integer赋值给int基本类型。
实际上该语句等价于:
Integer year = Integer.valueOf(2013);int year = year.intValue();
?通过调用实例对象的intValue方法将包装类转换成int基本类型。
?
包装类在逻辑运算中的应用。
1.比较两个包装类:
对于==和!=,比较的是它们的引用,而不是它们封装的值。比如:
Integer i = Integer.valueOf(2013);Integer j = Integer.valueOf(2013);if(i == j) {System.out.println("equals!");}else {System.out.println("Not equal!");}?输出结果是Not equal!。
对于>=,>,<,<=,比较的是它们携带的值。比如:
Integer i = Integer.valueOf(2012);Integer j = Integer.valueOf(2013);String msg = i < j ? "lt" : (i == j) ? "eq" : "gt";System.out.println(msg);
?输出结果是lt。
所以千万不要用==或者!=对两个包装类进行比较(它们比较的是引用!!)
?
2.比较两个混合类型(包装类和对应基本类型比较):
对于==,!=,<,<=,>,>=,首先会对包装类拆箱(调用实例对象的intValue方法),然后再来比较两个基本类型。比如:
Integer i = Integer.valueOf(2012);int j = 2013;String msg = (i >= j) ? "ge" : "lt";System.out.println(msg);
?输出结果是lt。
?
慎用装箱基本类型(包装类):考虑下面一个例子:
Long sum = 0;for(int i=0; i< Integer.MAX_VALUE;i++) { sum += i;}?由于粗心大意,将long写成了Long。这样在循环体中就会多次拆箱和装箱,造成性能影响。
?