zoukankan      html  css  js  c++  java
  • Integer的valueOf方法

    先上几个例子:

    1         Integer it1 = 140;
    2         Integer it2 = 140;
    3         System.out.println(it1 == it2);

    输出false。

    1         Integer it1 = 100;
    2         Integer it2 = 100;
    3         System.out.println(it1 == it2);

    输出true。

    很奇怪的是为什么一个是true一个是false。

    对这段代码反编译之后的结果如下:

    1     Integer it1 = Integer.valueOf(100);
    2     Integer it2 = Integer.valueOf(100);
    3     System.out.println(it1 == it2);

    从这段代码中可以看出Integer it1 = 100调用了Integer的valueOf方法,再来看看valueOf方法的源码:

    1 public static Integer valueOf(int i) {
    2         if(i >= -128 && i <= IntegerCache.high)
    3             return IntegerCache.cache[i + 128];
    4         else
    5             return new Integer(i);
    6     }

    从这段代码中可以看出,Integer内部维护了一个缓存数组cache,而这个缓存数组里缓存的是值的范围是:

    -128到127。

    所以在这个范围内的数字调用valueOf方法返回的都是同一个对象。

  • 相关阅读:
    代码模板
    DNSget Ip
    WC约束示使用
    下雨了
    Xml文件保存值不能及时更新
    代码不是艺术,而是达到目的的一种手段
    网站TCP链接暴增
    吐个槽吧
    正则表达式使用小注意
    Sereja and Two Sequences CodeForces
  • 原文地址:https://www.cnblogs.com/huashui/p/3234792.html
Copyright © 2011-2022 走看看