zoukankan      html  css  js  c++  java
  • java之装箱拆箱

     参考http://how2j.cn/k/number-string/number-string-wrap/22.html

    封装类

    所有的基本类型,都有对应的类类型
    比如int对应的类是Integer
    这种类就叫做封装类

    package digit;
     
    public class TestNumber {
     
        public static void main(String[] args) {
            int i = 5;
             
            //把一个基本类型的变量,转换为Integer对象
            Integer it = new Integer(i);
            //把一个Integer对象,转换为一个基本类型的int
            int i2 = it.intValue();
             
        }
    }

    Number类

    数字封装类有
    Byte,Short,Integer,Long,Float,Double
    这些类都是抽象类Number的子类

    package digit;
     
    public class TestNumber {
     
        public static void main(String[] args) {
            int i = 5;
             
            Integer it = new Integer(i);
            //Integer是Number的子类,所以打印true
            System.out.println(it instanceof Number);
        }
    }

    基本类型转封装类

    package digit;
     
    public class TestNumber {
     
        public static void main(String[] args) {
            int i = 5;
     
            //基本类型转换成封装类型
            Integer it = new Integer(i);
             
        }
    }

    封装类转基本类型

    package digit;
     
    public class TestNumber {
     
        public static void main(String[] args) {
            int i = 5;
     
            //基本类型转换成封装类型
            Integer it = new Integer(i);
             
            //封装类型转换成基本类型
            int i2 = it.intValue();
             
        }
    }

    自动装箱

    不需要调用构造方法,通过=符号自动把 基本类型 转换为 类类型 就叫装箱

    package digit;
     
    public class TestNumber {
     
        public static void main(String[] args) {
            int i = 5;
     
            //基本类型转换成封装类型
            Integer it = new Integer(i);
             
            //自动转换就叫装箱
            Integer it2 = i;
             
        }
    }

    自动拆箱

    不需要调用Integer的intValue方法,通过=就自动转换成int类型,就叫拆箱

    package digit;
      
    public class TestNumber {
      
        public static void main(String[] args) {
            int i = 5;
      
            Integer it = new Integer(i);
              
            //封装类型转换成基本类型
            int i2 = it.intValue();
             
            //自动转换就叫拆箱
            int i3 = it;
              
        }
    }

    int的最大值,最小值

    int的最大值可以通过其对应的封装类Integer.MAX_VALUE获取

    应该是自动装箱必须一一匹配

    但是拆箱,只要拆出来的基本类型,其范围小于左侧基本类型的取值范围,就可以。

    比如:

     Byte b = 5;
    
    Short s = 5;
    
    Integer i = 5; Long l = 5l;
    
    long x;
    
    x= b;
    
    x=s;
    
    x=i;
    
    x=l; 

    右边是类类型,左边的x是long基本类型,那么也可以自动拆箱

    以x=b为例,b自动拆箱出来时byte基本类型,byte的取值范围小于long,那么就不会出现编译错误。

  • 相关阅读:
    Docker-compose编排微服务顺序启动解决方案
    在笔记本上使用virtualbox搭建lvs dr 实验遇到的问题
    MongoDB安装配置(RedHat/CentOS)
    wget 用法
    Ubuntu查看crontab运行日志
    CentOS-6.5安装Zabbix 3.0.4
    centos 6 安装vsftpd与PAM虚拟用户
    python socket常用接口说明
    cmake 构建工程
    std::vector的下标访问和迭代器访问的效率
  • 原文地址:https://www.cnblogs.com/lijingran/p/9127004.html
Copyright © 2011-2022 走看看