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

    设置以后的结果:

  • 相关阅读:
    洛谷P3313&BZOJ-3531【SDOI2014】旅行--线段树动态开点+树链剖分
    BZOJ3932【CQOI2015】任务查询系统&洛谷P3168--主席树区间前K小+差分
    博客中的代码CE说明
    栗栗的书架--洛谷P2468【SDOI2010】&BZOJ 1926二分+前缀和+主席树
    hdu1010--Tempter of the Bone(迷宫)
    hdu1242 Rescue DFS(路径探索题)
    hdu 1241--入门DFS
    注意引用的用法
    划分树---hdu4417---区间查找(不)大于h的个数
    程序员能力矩阵
  • 原文地址:https://www.cnblogs.com/cleveraboy/p/9967970.html
Copyright © 2011-2022 走看看