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?
Flip the condition around, and check against the boxed Integer:
!Integer.valueOf(0).equals(m.get("status"))