【问题标题】:comparing the values of two Integers比较两个整数的值
【发布时间】:2012-04-23 17:48:52
【问题描述】:

我想比较两个整数类型数组的值。当我比较它们的确切值时,我得到了错误的答案,而当我将它们与 Arrays.equals 进行比较时,我得到了正确的答案:

    Integer a[]=new Integer[2];
    Integer b[]=new Integer[2];
    a[0]=138;
    a[1]=0;
    b[0]=138;
    b[1]=0;
    boolean c;
    c=a[0]==b[0];//c is false
    c=Integer.valueOf(a[0])==Integer.valueOf(b[0]);//c is false
    c=Arrays.equals(a, b);//c is true

【问题讨论】:

    标签: java arrays comparison integer


    【解决方案1】:

    您正在寻找intValue,而不是Integer.valueOf(虽然很容易看出您是如何让他们感到困惑的!):

    c = a[0].intValue() == b[0].intValue();
    

    Java 具有原始类型(intbytedouble 等)以及在需要对象的情况下与它们对应的引用类型(对象)。您执行 a[0] = 138; 的代码是在 Integer 实例中自动装箱原始值 138。

    intValue 返回Integer 实例包含的原语intInteger.valueOf 用于获取 Integer 实例(来自 intString - 在您的情况下,它将通过自动取消装箱您的 Integer 引用来使用 valueOf(int))。

    您也可以这样做:

    c = (int)a[0] == (int)b[0];
    

    ...这将触发自动拆箱。

    the specification 中有关装箱(包括自动装箱和拆箱)的更多信息。

    【讨论】:

    • 感谢您的完整回答。a 和 b 是哈希值,这就是它们是整数的原因。
    【解决方案2】:

    您正在代码中进行隐式类型转换(自动装箱)。

    行:

    a[0]=138;
    

    实际上翻译为:

    a[0] = Integer.valueOf(138);
    

    创建一个整数实例。问题是此方法缓存了从 -128 到 127(How large is the Integer cache?) 的整数,并为高于 127 的值创建新实例,因此 == 比较返回 false。

    /**
     * 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);
    }
    

    注意a[0]的实际类型是Integer,所以你可以写

    c=a[0].equals(b[0]);
    

    这将返回 true。

    【讨论】:

      【解决方案3】:

      由于数组,我认为内部值不会自动为您拆箱。如果您有 int[] 而不是 Integer[],这可能会起作用

      【讨论】:

        猜你喜欢
        • 2012-06-05
        • 1970-01-01
        • 1970-01-01
        • 2019-07-04
        • 2022-01-09
        • 1970-01-01
        • 2014-10-25
        • 2023-03-26
        • 1970-01-01
        相关资源
        最近更新 更多