==在Integer中和String类中的使用问题

来源:互联网 发布:淘宝直播审核条件 编辑:程序博客网 时间:2024/05/21 14:56
双等于号在Integer中和String类中的使用问题
/**
* Java中new出来的东西存放在heap中,==是判断两个对象的引用是否相同
* 局部变量存放在Stack中,Integer t1等用于存放new出来的东西的引用地址
*/
public static void testInteger(){
System.out.println("======双等于号在Integer中的使用========");
Integer t1 = new Integer(5);
Integer t2 = new Integer(5);
System.out.println(t1==t2);
Integer t3 = 5;//Integer对象中IntegerCache缓存对象,缓存了-128-127的数
Integer t4 = 5;//从缓存中拿到同一个
System.out.println(t3==t4);
Integer t5 = 128;//超出了IntegerCache缓存的界限,需要自动装包成新的对象
Integer t6 = 128;
System.out.println(t5==t6);
System.out.println("=============比较字符串=========");
//String中有个String pool池对象:如果字符串已经存在,则直接拿出来指向stack
//不存在,则创建一个新的String对象
String s1 = "hello";
String s2 = "hello";//已经存在,直接拿取
System.out.println(s1==s2);
String s3 = new String("hello");//new出来的对象,分配新的内存引用
String s4 = new String("hello");
System.out.println(s3==s4);
String s5 = "hello";//创建一个
String s6 = new String("hello");//创建另外一个
System.out.println(s5==s6);
}
Integer类中有一个Integer缓存对象IntegerCache class
private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];
        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                int i = parseInt(integerCacheHighPropValue);
                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() {}
    }
0 0
原创粉丝点击