how to get equality behavior with autoboxing comparing with Object and int as Java 7 with Java8

58 Views Asked by At

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?

2

There are 2 best solutions below

0
Andy Turner On BEST ANSWER

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

!Integer.valueOf(0).equals(m.get("status"))
0
Alex Shesterov On

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")));
}