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,那么就不会出现编译错误。

  • 相关阅读:
    关于java集合框架(二):List
    仪式感
    java的foreach(增强for循环)
    关于Java集合框架(一):概述与Set
    重新开始
    简单fork循环分析
    fork,写时复制(copy-on-write),vfork
    树莓派换源
    Windows下TexLive2018环境配置及检测
    Linux下高精度时间
  • 原文地址:https://www.cnblogs.com/lijingran/p/9127004.html
Copyright © 2011-2022 走看看