zoukankan      html  css  js  c++  java
  • java关于Integer设置-128到127的静态缓存

    今天在一个java群里,看到有个群友问到如下为什么第一个为true,第二个为false。  

      System.out.println(Integer.valueOf("50")==Integer.valueOf("50"));   //true
      System.out.println(Integer.valueOf("200")==Integer.valueOf("200"));  //false

      由于一开始他问的第二句,我还想当然的以为是new的对象,肯定不一样,但是为什么第一句为true呢,后来通过查找资料发现

      1、https://www.zhihu.com/question/29879295/answer/102396251  

      2、http://blog.csdn.net/chengzhezhijian/article/details/9628251

    复制代码
        /**
         * Returns a <tt>Integer</tt> instance representing the specified
         * <tt>int</tt> value.
         * If a new <tt>Integer</tt> instance is not required, this method
         * should generally be used in preference to the constructor
         * {@link #Integer(int)}, as this method is likely to yield
         * significantly better space and time performance by caching
         * frequently requested values.
         *
         * @param  i an <code>int</code> value.
         * @return a <tt>Integer</tt> instance representing <tt>i</tt>.
         * @since  1.5
         */
        public static Integer valueOf(int i) {
            if(i >= -128 && i <= IntegerCache.high)
                return IntegerCache.cache[i + 128];
            else
                return new Integer(i);
        }
    复制代码

      

    复制代码
     private static class IntegerCache {
            static final int high;
            static final Integer cache[];
    
            static {
                final int low = -128;
    
                // high value may be configured by property
                int h = 127;
                if (integerCacheHighPropValue != null) {
                    // Use Long.decode here to avoid invoking methods that
                    // require Integer's autoboxing cache to be initialized
                    int i = Long.decode(integerCacheHighPropValue).intValue();
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - -low);
                }
                high = h;
    
                cache = new Integer[(high - low) + 1];
                int j = low;
                for(int k = 0; k < cache.length; k++)
                    cache[k] = new Integer(j++);
            }
    
            private IntegerCache() {}
        }
    复制代码

      valueOf会将常用的值(-128 to 127)cache起来。当i值在这个范围时,会比用构造方法Integer(int)效率和空间上更好。

      

  • 相关阅读:
    webstorm
    web大文件上传(web应用---SSH框架)
    Webuploader 大文件分片上传
    百度Webuploader 大文件分片上传(.net接收)
    java使用WebUploader做大文件的分块和断点续传
    大文件上传插件webupload插件
    使用Webuploader大文件分片传输
    使用原生Java Web来实现大文件的上传
    Java实现浏览器端大文件分片上传
    怎样使用word2013发布csdn博客
  • 原文地址:https://www.cnblogs.com/zhuyeshen/p/11753768.html
Copyright © 2011-2022 走看看