IDEA-包装类的概述、基本使用、自动装箱、拆箱

包装类:
基本数据类型的数据,使用起来非常的方便,但是没有对应的方法来操作这些数据,所以我们可以使用一个类,把基本类型的数据包装起来,这个类叫包装类,在包装类中可以定义一些方法,用来操作基本类型的数据。

装箱与拆箱
基本类型与对应的包装类对象之间,来回转换的过程称为“装箱”与“拆箱”:
装箱:从基本类型转换为对应的包装类对象。
拆箱:从包装类对象转换对应的基本类型。

装箱:
    把基本类型的数据,包装到包装类中(基本类型的数据 -> 包装类)
        构造方法:
        Integer(int value)
          构造一个新分配的 Integer 对象,它表示指定的 int 值。
        Integer(String s)
          构造一个新分配的 Integer 对象,它表示 String 参数所指示的 int 值。
        静态方法:
        static Integer valueOf(int i)
          返回一个表示指定的 int 值的 Integer 实例。
        static Integer valueOf(String s)
          返回保存指定的 String 的值的 Integer 对象。
    拆箱:
    在包装类中,取出基本类型的数据(包装类 -> 基本类型的数据)
        成员方法:
           int intValue()int 类型返回该 Integer的值。
 */
public class Demo01Integer {
    public static void main(String[] args) {
        //把基本类型的数据,包装到包装类中(基本类型的数据 -> 包装类)
        //构造方法
        Integer in1 = new Integer(1);
        System.out.println(in1);//1 重写了toString方法
        Integer in2 = new Integer("1");
        System.out.println(in2);
        //静态方法
        //只能使用基本数据类型,否则报数据格式化异常//
        //Integer in3 = Integer.valueOf("a");//NumberFormatException数字格式化异常
       // System.out.println(in3);
        Integer in4 = Integer.valueOf(1);
        System.out.println(in4);

        //拆箱:在包装类中,取出基本类型的数据(包装类 -> 基本类型的数据)
        int i = in1.intValue();
        System.out.println("i:" + i);

    }
}

自动装箱与自动拆箱

import java.util.ArrayList;
/*
    自动装箱与自动拆箱:
        基本类型的数据和包装类之间可以自动的相互转换
        JDK 1.5+ 出现的新特性
 */
public class Demo02Integer {
    public static void main(String[] args) {
        /*
            自动装箱:直接把int类型的整数赋值给包装类
            Integer in = 1; 就相当于Integer in = new Integer(1);
         */
        Integer in = 1;
        /*
            自动拆箱: in是包装类,无法直接参与运算,可以自动转换成为基本类型的数据,再参与计算。
            in + 2; 就相当于 in.intValue() + 3 = 3;
            in = in + 2; 就相当于 in = new Integer(3) 自动装箱
         */
        in += 2;
        System.out.println(in);
        //ArrayList集合无法直接存储整数,可以存储Integer包装类
        ArrayList<Integer> list = new ArrayList<>();
        list.add(1);// 自动装箱 list.add(new Integer(1));
        int a = list.get(0);//自动拆箱 list.get(0).iontValue();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值