zoukankan      html  css  js  c++  java
  • Java: Integer用==比较时127相等128不相等的原因

    直接看问题吧

    1    for (int i = 0; i < 150; i++) {
    2                 Integer a = i;
    3                 Integer b = i;
    4                 System.out.println(i + " " + (a == b));
    5             }部分结果

    结果为:

    .....
    124 true 125 true 126 true 127 true 128 false 129 false 130 false 131 false

    黑人问号?  为什么到128就不行了? 问题在哪里?  (道行太浅!  为什么就认为 false是异端)

    查了一下java会自动将(i)int类型转换为Integer类型,即

     1 Integer a = Integer.valueOf(1); 

    等等,  再仔细思考一下。  结合上述例子,每一次 i和j都会被装箱为Integer   既然是对象,那就不应该返回true了啊?。  那我就用看看 i和j的内存地址()

    for(int i=0;i<150;i++){
        Integer a=i;
        Integer b=i;
        System.out.println(a+" "+b+" "+System.identityHashCode(a)+" "+System.identityHashCode(b));
    }

    部分结果:


    1
    123 123 1531448569 1531448569 2 124 124 1867083167 1867083167 3 125 125 1915910607 1915910607 4 126 126 284720968 284720968 5 127 127 189568618 189568618 6 128 128 793589513 1313922862 7 129 129 495053715 1922154895

    竟然....... 竟然从0到127不同时候自动装箱得到的是同一个对象!从128开始才是正常情况。  那看看源码

        /**
         * Returns an {@code Integer} instance representing the specified
         * {@code int} value.  If a new {@code Integer} 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.
         *
         * This method will always cache values in the range -128 to 127,
         * inclusive, and may cache other values outside of this range.
         *
         * @param  i an {@code int} value.
         * @return an {@code Integer} instance representing {@code i}.
         * @since  1.5
         */
        public static Integer valueOf(int i) {
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }

    我大概的翻译一下啊,  数再-128到127之间,就直接在缓存里取。否则就返回一个新对象。  哦哦这下问题解决了

  • 相关阅读:
    五一拆装机学习
    msgbox函数和inputbox函数应该注意的几点
    西游记(3)
    刚刚开通csdn
    c# 快捷键
    JavaBean的属性(Simple,Indexed,Bound,Constrained)【收藏】
    SQL查询语句使用【收藏】
    .NET 对实现IPersistStream接口的对象进行保存和读取
    创建控件数组
    常用数据库JDBC连接写法【收藏】
  • 原文地址:https://www.cnblogs.com/smellpawn/p/10825199.html
Copyright © 2011-2022 走看看