Java中的装箱,拆箱详解

来源:互联网 发布:期货数据分析 编辑:程序博客网 时间:2024/03/29 17:12

Java中的装箱,拆箱详解

什么是装箱和拆箱

首先看一下java的8种基本类型:



对于每一种基本类型都有其对应的包装器类型。
所谓装箱就是把基本类型装换为包装器类型,所谓拆箱就是把包装器类型转换为基本类型。

装箱操作

/** *  * @author wangcan * */public class Test {    public static void main(String[] args) {        Integer num = 100;    Integer num2 = Integer.valueOf(100);    }}

Intege num = 100 实际上也是调用了Integer.valueOf ,所谓的自动装箱即时默认执行了这个过程,所以我们可以直接使用Intege num = 100 

拆箱操作

/** *  * @author wangcan * */public class Test {    public static void main(String[] args) {        Double d = 1.23d;    double c = d;//自动拆箱    double e = d.doubleValue();//Returns the double value of this Double object.    }}

一道小题

/** *  * @author wangcan * */public class Test {public static void main(String[] args) {//注:== 判断的是是否是同一个对象  equal判断的是内容String str1 = "abc";String str2 = "abc";System.out.println(str2 == str1); // 输出为 trueSystem.out.println(str2.equals(str1)); // 输出为 trueString str3 = new String("abc");String str4 = new String("abc");System.out.println(str3 == str4); // 输出为 falseSystem.out.println(str3.equals(str4)); // 输出为 true}}

为什么要有装箱

装箱和拆箱是为了编程模式的简单,任何对象都应当可以赋给Object,对于引用类型赋给Object没问题,都是引用类型,只是一个引用的赋值,但是值类型赋给Object就有问题了,因为值类型没有引用,为了造出一个引用,也就有了装箱操作。


0 0
原创粉丝点击