简体   繁体   中英

comparison if statment should be called twice but it is only called once when comparing an Integer

I have a function that takes a Integer array and a boolean array. If the value in the Integer array is the highest value and the boolean array is true, the value in the trackerArray is set to true. This is a simplified version of my code that produces the error...

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}
    }
}

The trackerArray should be {false,true,false,true,false}, instead it is {false,true,false,false,false}. The if statment should be triggered twice but instead it is only triggered once. Why is this?

You should use Integer.equals() , which compares values, not Integer == Integer , which compares object references. Your current code literally says "is the second instance of 200 the same instance as the first instance of 200"

Two options:

  1. Change iHighestSum to int ie int iHighestSum = 0; Java will auto-unbox the Integer to get its int value, then you will be comparing ints , so it's valid to use ==
  2. Change your comparison to use equals() : if(integerArray[c].equals(iHighestSum))

As an interesting side note, your code would pass if you changed the values 200 to 127 (or less). This is because the JVM keeps fixed, reusable Objects inside the Integer class for all values between -128 and 127 (ie a "byte"), ie Integer[] integerArray = new Integer[] { 75, 127, 75, 127, 75 }; passes!

So in summary, either of these changes will make your code function correctly:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM