zoukankan      html  css  js  c++  java
  • 并不简单的Integer

    Integer是一个看着挺简单的,其实还是有点不一样,Integer是一个int的包装类,它是可以起到缓存作用的,在java基础里说过它的范围是(-128-127)在这个返回是有缓存的,不会创建新的Integer对象,并且可以设置它的最大值,通过设置VM参数。

    下面先看一下源码:

     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() {}
        }
    // value of java.lang.Integer.IntegerCache.high property (obtained during VM init)
        private static String integerCacheHighPropValue;
        static void getAndRemoveCacheProperties() {
            if (!sun.misc.VM.isBooted()) {
                Properties props = System.getProperties();
                integerCacheHighPropValue =
                    (String)props.remove("java.lang.Integer.IntegerCache.high");
                if (integerCacheHighPropValue != null)
                    System.setProperties(props);  // remove from system props
            }
        }

    通过设置VM的java.lang.Integer.IntegerCache.high可以调整它的最大值。虽然它是在一个静态代码块里是一个常量,但是是在初始化的时候赋值的,所以没什么影响。

    演示修改JVM参数(eclipse):

    package test1;
    
    public class Demo1 {
        
        public static void main(String[] args) {
            System.out.println(Integer.valueOf(200)==Integer.valueOf(200));
        }
    
    }

    输出结果:

    false

    怎么修改呢,看下面?

    点击自己创建的项目,右键->Debug as ->Debug Configurations ->JavaApplication->点击自己的项目->Arguments->VM arguments设置->Apply->Debug

    设置以后的结果:

  • 相关阅读:
    【高端黑】软件工程师去理发店
    [SQL]用于提取组内最新数据,左连接,内连接,not exist三种方案中,到底谁最快?
    Oracle数据库访问客户端 sqldeveloper-19.2.1.247.2212-x64 下载
    《木兰辞》中最精彩的六句
    SqlComparison
    别让情绪扰乱心绪
    50年内神秘消失的恒星
    java命名总结
    针对nginx,来具体聊聊正向代理与反向代理 (转载)
    Nginx可以做什么?(转载)
  • 原文地址:https://www.cnblogs.com/cleveraboy/p/9967970.html
Copyright © 2011-2022 走看看