【问题标题】:comparison if statment should be called twice but it is only called once when comparing an Integer比较 if 语句应该被调用两次,但在比较 Integer 时只调用一次
【发布时间】:2011-07-13 22:34:21
【问题描述】:

我有一个函数,它接受一个整数数组和一个布尔数组。如果 Integer 数组中的值为最大值且布尔数组为 true,则将 trackerArray 中的值设置为 true。这是我的代码的简化版本,它会产生错误...

package com.thisis.a.test;

public class ThisIsATest {

    public static void main(String[] args){
        Integer[] integerArray = new Integer[]{75,200,75,200,75};
        boolean[] booleanArray = new boolean[]{false,true,false,true,false};
        boolean[] trackerArray   = new boolean[]{false,false,false,false,false};

        Integer iHighestSum = 0;
        for(int c = 0; c < booleanArray.length; c++){
            if(booleanArray[c] == true)
                if(integerArray[c] > iHighestSum)
                    iHighestSum = integerArray[c];
        }

        for(int c = 0; c < booleanArray.length; c++){
            if(booleanArray[c] == true)
                if(integerArray[c] == iHighestSum) 
                    trackerArray[c] = true; // this if statement should be called twice
        }

        // trackerArray should be {false,true,false,true,false} 
        // instead it is {false,true,false,false,false}
    }
}

trackerArray 应该是 {false,true,false,true,false},而不是 {false,true,false,false,false}。 if 语句应该被触发两次,但它只被触发一次。这是为什么呢?

【问题讨论】:

    标签: java


    【解决方案1】:

    您应该使用比较值的Integer.equals(),而不是比较对象引用的Integer == Integer。您当前的代码字面意思是“是 200 的第二个实例与 200 的第一个实例相同的实例

    两种选择:

    1. 将 iHighestSum 更改为intint iHighestSum = 0; Java 将auto-unbox Integer 获取其int 值,然后您将比较ints,因此使用== 是有效的
    2. 将比较更改为使用equals()if(integerArray[c].equals(iHighestSum))

    作为一个有趣的附注,如果您将值 200 更改为 127(或更少),您的代码将会通过。这是因为 JVM 为 -128 和 127 之间的所有值(即“字节”)在 Integer 类中保留了固定的、可重用的对象,即 Integer[] integerArray = new Integer[] { 75, 127, 75, 127, 75 }; 传递!

    因此,总而言之,这些更改中的任何一个都会使您的代码正常运行:

    ...
    int iHighestSum = 0;
    ...
    if(integerArray[c].equals(iHighestSum))
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 2018-03-29
      • 2021-11-18
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多