概述
public class JavaBase {
public static void main(String[] args) {
autoBoxing();
}
/**
* 装箱就是自动将基本数据类型转换为包装器类型(int-->Integer);调用方法:Integer的
* valueOf(int) 方法
* 拆箱就是自动将包装器类型转换为基本数据类型(Integer-->int)。调用方法:Integer的intValue方 法
*/
public static void autoBoxing(){
Integer a1 = new Integer(127); //jdk 1.5 之前
Integer a = 127; //jdk 1.5以后
Integer b = 127;
Integer c = 128;
Integer d = 128;
System.out.println(a1 == a);//false
System.out.println(a == b); //true 原因在:Integer.valueOf()方法 -128 ~127 会缓存起来
System.out.println(c == d); //false
Integer.valueOf(127);
Integer.valueOf(-128);
/**
* public static Integer valueOf(int i) {
* if (i >= IntegerCache.low && i <= IntegerCache.high)
* return IntegerCache.cache[i + (-IntegerCache.low)];
* return new Integer(i);
* }
*/
/**
* public static Integer valueOf(int i) {
* if (i >= IntegerCache.low && i <= IntegerCache.high)
* return IntegerCache.cache[i + (-IntegerCache.low)];
* return new Integer(i);
* }
*/
Long l1 = 127L;
Long l2 = 127L;
Long l3 = 128L;
Long l4 = 128L;
System.out.println(l1 == l2); //true
System.out.println(l3 == l4); //false
Long.valueOf(127);
Long.valueOf(-128);
/**
*public static Long valueOf(long l) {
* final int offset = 128;
* if (l >= -128 && l <= 127) { // will cache
* return LongCache.cache[(int)l + offset];
* }
* return new Long(l);
* }
*/
Double d1 = 127.0;
Double d2 = 127.0;
Double d3 = 128.0;
Double d4 = 128.0;
Double.valueOf(127.0);
//原因: 在某个范围内的整型数值的个数是有限的,而浮点数却不是。所有没有缓存
/**
* public static Double valueOf(double d) {
* return new Double(d);
* }
*/
System.out.println(d1 == d2); //false
System.out.println(d3 == d4); //false
}
}
最后
以上就是高贵龙猫为你收集整理的java基础之基础类型的自动装箱的全部内容,希望文章能够帮你解决java基础之基础类型的自动装箱所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复