船過水無痕

Java | Web | Architecture
posts - 12, comments - 0, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

Java装箱与拆箱

Posted on 2009-12-28 16:01 zdxue 阅读(342) 评论(0)  编辑  收藏
 1 package org.zdxue.blog.persistent.dao.impl.hibernate;
 2 
 3 /**
 4  * ==号是比较两个基本类型是否相等,或者比较两个对象引用是否相同
 5  *
 6  * @version 1.0 - 2009-12-28
 7  * @author zdxue     
 8  */
 9 public class T {
10 
11     public static void main(String[] args) {
12         Integer i1 = 128;
13         Integer i2 = 128;
14         int i3 = 128;
15         int i4 = 128;
16         Integer i5 = 127;
17         Integer i6 = 127;
18         
19         Long long1 = 128L;
20         Long long2 = 128L;
21         long long3 = 128L;
22         long long4 = 128L;
23         long long5 = -128L;
24         long long6 = -128L;
25         
26         //-128 ~ 127之间数值装箱时会共享内存副本, 超过这个范围,则不会共享引用,即对象地址将不同
27         
28         System.out.println(i1 == i2); //实质是比较两个不同引用 false
29         System.out.println(i5 == i6); //实质是比较两个相同(共享)引用true
30         System.out.println(i1 == i3); //先将i1拆箱,然后比较基本类型 true
31         System.out.println(i1.equals(i4)); //先将i4装箱,然后比较基本类型 true
32         
33         System.out.println(long1 == long2);//两个引用不同 false
34         System.out.println(long5 == long6);//共用副本 true
35         System.out.println(long1 == long3);//long1先拆箱, 在比较 true
36         System.out.println(long2.equals(long4));//long4先装箱, 再equals, true
37     }
38 }
39 

只有注册用户登录后才能发表评论。


网站导航: