zoukankan      html  css  js  c++  java
  • 自动封箱和拆箱

    Integer 中

    public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }        
    

      

    如果没有设置IntegerCache.high的值,默认为127,也就是说值在-128~127之间,返回的都是同一个对象。
    1. Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;
      System.out.println(f1 == f2);
      System.out.println(f3 == f4);
    输出结果是:
    1. true
    2. false
    Long、Byte、Short同理。
    Boolean中
     
      public static Boolean valueOf(boolean b) {
        return (b ? TRUE : FALSE);
      }
    Character中
      
    public static Character valueOf(char c) {
        if (c <= 127) { // must cache
            return CharacterCache.cache[(int)c];
        }
        return new Character(c);
    }    
    Double中
    1. public static Double valueOf(double d) {
        return new Double(d);
      }
       
    对于任何的duoble类型的数据,每次都是从新装箱,生一个新的对象;Float类型同理。
    1. public static void main(String[] args) {
      Integer a = 1;
      Integer b = 2;
      Integer c = 3;
      Integer d = 3;
      Integer e = 321;
      Integer f = 321;
      Long g = 3L;
      Long h = 2L;
      System.out.println(c==d);//不用解释了把,关于Integer中写的很清楚-128~127都是自动装箱成同一个对象了
      System.out.println(e==f);//看Integer中解释
      System.out.println(c==(a+b));//因为+所有a和b自动拆箱,会各自调用IntValue()方法,得到值后会在调用Integer.valueOf
      System.out.println(c.equals(a+b));
      System.out.println(g==(a+b));
      System.out.println(g.equals(a+b));
      System.out.println(g.equals(a+h));//因h是long类型,a则自动向上转型为Long
      }
    输出结果:
    1. true
    2. false
    3. true
    4. true
    5. true
    6. false
    7. true
    8. true
  • 相关阅读:
    JAVA中HashMap相关知识的总结(一)
    linux进阶之路(三):vi/vim编辑器
    linux进阶之路(二):linux文件目录
    linux进阶之路(一):linux入门
    linux:lrzsz安装
    一:阿里云服务器使用及后台环境搭建
    第二篇:线程七种状态
    Git log
    redis3.0 集群实战3
    详解Linux chgrp和chown命令的用法
  • 原文地址:https://www.cnblogs.com/woniu4/p/4765754.html
Copyright © 2011-2022 走看看