JDK5.0新特性-自动装箱/拆箱

本文详细介绍了Java中自动装箱与拆箱的过程及应用,包括基本数据类型与包装类之间的转换,并通过实例展示了如何在集合中使用这些特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

lJDK5.0的语法允许开发人员把一个基本数据类型直接赋给对应的包装类变量, 或者赋给 Object 类型的变量,这个过程称之为自动装箱。
l自动拆箱与自动装箱与之相反,即把包装类对象直接赋给一个对应的基本类型变量。
l典型应用:
List list = new ArrayList();
list.add(1);
int j = (Integer)list.get(0);
package cn.itcast.autobox;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class Demo {

    @Test
    public void demo1() {
        // 自动装箱
        // Integer in=new Integer(10);
        Integer in = 10;
        // 自动拆箱
        int i = new Integer(10); // 调用intValue()方法
    }

    // 自动拆箱与装箱应用----集合. 集合中的元素全是Object
    @Test
    public void demo2() {
        List<Integer> list = new ArrayList<Integer>();

        list.add(10); // 进行了自动的装箱操作.
        
        int n=list.get(0);
    }
    
    //关于Integer的笔试题
    @Test
    public void dmo3(){
//        Integer in1=new Integer(100);
//        Integer in2=new Integer(100);
//        
//        Integer in3=100;  //IntegerCache[100];
//        Integer in4=100;
//        
//        System.out.println(in1==in2); //false
//        System.out.println(in2==in3); //false
//        System.out.println(in3==in4); //true
        
        
        Integer in1=new Integer(1000);
        Integer in2=new Integer(1000);
        
        Integer in3=1000;  //new Integer(100);
        Integer in4=1000;   
        
        System.out.println(in1==in2); //false
        System.out.println(in2==in3); //false
        System.out.println(in3==in4); //false
    }
}

1.自动装箱与拆箱.
java中的包装类.
包装类是对java中的基本数据进行包装,可以将基本类型包装成类类型。

基本数据类型

四类八种.
1.整型 byte short int long
2.浮点型 float double
3.字符 char
4.布尔 boolean

包装类
Byte Short Integer Long
Float Double
Character
Boolean

自动拆箱
直接将Integer对象赋值给int

自动装箱
直接将int赋值给Integer。


//对于Integer类它的自动装箱时,如果int值是在-128----127之间是从IntegerCache中取出的一个值,
如果不在这个范围内是重新new Integer()

转载于:https://www.cnblogs.com/spadd/p/4190829.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值