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

  • 相关阅读:
    用C#生成足够随机的互不相同的随机数
    CRM
    Asp.net2.0部署时TreeView控件无法正常显示没有图片的问题
    javascript解析json
    jQuery插件倒计时。
    ASP.NET MVC + jQuery + Newtonsoft.Json 快乐的AJAX
    .NET中DataSet转化Json工具类
    jQuery load html
    jQuery 使用注意点技巧1
    WEB页面多语言支持解决方案
  • 原文地址:https://www.cnblogs.com/lijingran/p/9127004.html
Copyright © 2011-2022 走看看