0

We have code that needs to upgrade from Java 7 to Java 8. Lot's of snippets like this:

public class TestJava8 {

    private static void TestIntegerConversion(){
        Map<String, Object> m = new HashMap<>();
        System.out.println(m.get("status") != 0);
    }

    public static void main(String[] argvs){
        TestIntegerConversion();
    }
}

We have take advantage that m.get("status") != 0 returns false only if there is a int value number for key "status" and it's not 0. If the "status" is 0 or omited, it will return true. which is the desired behavior.

But when upgrading to Java 8 it will complain that incomparable types: java.lang.Object and int error, and if we do a force cast (int)m.get("status") there will be an Exception instead of return true when "status"was omitted.

So is there an equality behavior trick that could make equality behavior like Java 7?

Most Noble Rabbit
  • 2,728
  • 2
  • 6
  • 12
armnotstrong
  • 8,605
  • 16
  • 65
  • 130
  • How about using [`getOrDefault`](https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#getOrDefault-java.lang.Object-V-)? – khelwood May 07 '21 at 09:13
  • You might get away by replacing `0` with `Integer.valueOf(0)` , but I'd suggest to get rid of that "advantage", which rather indicates unclean use of (auto)boxing, BTW never compare `Integer` instances using `==`, rather use `equals()` – Gyro Gearless May 07 '21 at 09:27

2 Answers2

1

Flip the condition around, and check against the boxed Integer:

!Integer.valueOf(0).equals(m.get("status"))
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

You can create a static utility function which explicitly does what you need. It would also be helpful if you ever need to change this status logic globally.

/**
 * Returns true if value is null or a non-integer or a non-zero integer.
*/
public static boolean isNonZeroOrMissingStatusValue(final Object value) {
    return !isZeroStatusValue(value);
}

/**
 * Returns true if value is an integer zero.
*/
public static boolean isZeroStatusValue(final Object value) {
    return (value instanceof Integer) // this will be false if value is null
        && ((Integer) value).intValue() == 0;
}

...

private static void TestIntegerConversion(){
    Map<String, Object> m = new HashMap<>();
    System.out.println(isNonZeroOrMissingStatusValue(m.get("status")));
}
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103