码迷,mamicode.com
首页 > 编程语言 > 详细

[java基础] java中的自动装箱与自动拆箱

时间:2015-06-05 11:45:31      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

自动装箱的一个例子:

Integer i = 1; //实际上是执行了Integer i = Integer.valueOf(1)

 

自动拆箱的一个例子:

 

Integer a =1;
int b = a; //自动拆箱就是从对象中把基本数据取出来

 

Integer自动拆箱的一个好玩的例子:

Integer a = 100;
Integer b = 100;
System.out.println(a==b); // true

Integer c = 200;
Integer d = 200;
System.out.println(c == d); // false

原因如下:

 public static Integer valueOf(int i) {
	final int offset = 128;
	if (i >= -128 && i <= 127) { // must cache 
	    return IntegerCache.cache[i + offset];
	}
        return new Integer(i);
    }

并不是所有的valueOf都是这么玩的,Float.valueOf 就是直接返回一个 新对象。

[java基础] java中的自动装箱与自动拆箱

标签:

原文地址:http://www.cnblogs.com/simple-code/p/4553931.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!