java integer对象判断两个数字是否相等

java integer对象判断两个数字是否相等,不一定对   

问题发生的背景:javaweb的项目,起先,因为在java中实体类中的int类型在对象初始化之后会给int类型的数据默认赋值为0,这样在很多地方就会出现不必要的错误,比如没有判断之后就来计算分页,那么就可能出现页码为负数的情况,同时我也看了一片相关的blog,大概意思就是在javaweb中出现的这个问题,尽量不要用int。

好了受了这些影响,我在实体类里很多地方就用了integer类型,前几天都没有发现问题,在昨天做一个数据库相关的操作时,要将两个实体类的某些属性进行比较,(两个实体类中产品的Id)数据也比较巧,id=127 接下来就是id=132,然后在循环中发现127以前的数据比较结果为相等,127以后,从132开始比较时,后面所有的记录都不相等,奇怪了,132明明等于132啊,说到这里有的朋友应该猜到了并且笑了。好吧。还有朋友也会和我第一次遇到这个问题一样不明白啊。好,先看demo

 

public void testIntegerAndInt() {
        Integer a = 128;
        Integer b = 128;
        if (a==b)
        {
            System.out.print("Integer Compare Integer : ");
            System.out.println("Y");
        }else
        {
            System.out.print("Integer Compare Integer : ");
            System.out.println("N");
        }
        Integer m = 127;
        Integer n = 127;
        if (m==n)
        {
            System.out.print("int Compare int : ");
            System.out.println(" Y ");
        }
        else
        {
            System.out.print("int Compare int : ");
            System.out.println(" N ");
        }
    }

 

看到了吧,2X2应该由4种组合,但是现在之后2中剩余的来中就不测试了,如果感兴趣可以自己试试

下面在深入的看看为啥

   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) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }
大概意思就是-128到127之间不会封装对象而是用常量池的值,不在这个范围才会创建对象。

最后今天无意间发现了一个很有用的blog

http://blog.csdn.net/jackfrued/article/details/44921941

收藏了

posted @ 2015-10-12 00:44  牵牛花  阅读(13115)  评论(0编辑  收藏  举报