Reputation: 2615
Map<String,Integer> m;
m = new TreeMap<String,Integer>();
Is it good practice to add the following cast just to avoid the null pointer exception when m.get() is null.
System.out.println( ((Integer) 8).equals( m.get("null") ) ); // returns false
Alternatively with a prior null check it starts to look a bit ugly.
System.out.println( m.contains("null") != null && m.get("null").equals( 8 ) );
Is there a better way to write this? Thanks.
Upvotes: 11
Views: 25319
Reputation: 1015
You can use Objects.equals
int foo = 1;
Integer bar = null;
Objects.equals(foo, bar);
Upvotes: 1
Reputation: 17697
To expand the accepted answer: i find myself having to check the equality of 2 Integer variables which might or might not be null.
So my solution would be:
boolean equals = Optional.ofNullable(objectA.getNullableInteger()).equals(Optional.ofNullable(objectB.getNullableInteger());
Upvotes: 1
Reputation: 229264
No, because it will not work. You can't compare two Integer
with ==
, as that compares references and not the integer values. See more info in this question
You'll need a helper method, such as:
boolean safeIntegerCompare(Integer a, int b)
{
if (a != null)
return a.intValue() == b;
return false;
}
Upvotes: 8
Reputation: 25459
I try to avoid casts whenever possible, so I'd rather use the following, which also looks nicer in my opinion:
Integer.valueOf(8).equals(m.get("null"))
Upvotes: 11
Reputation: 62874
The ==
operator doesn't compare values, but references.
You should use the .equals()
method, instead, applied to the Integer
variable (for which you are sure that is not null
and NPE won't be thrown):
Integer eight = 8; //autoboxed
System.out.println(eight.equals(m.get("null")));
This will print false
even the m.get("null")
returns null
.
Upvotes: 9
Reputation: 49804
If only one of the arguments may be null
(as is the case when you're comparing an unknown value to a constant), use equals()
like this:
Integer foo = Integer.valueOf(8); // you could write Integer foo = 8; here too but I prefer to avoid autoboxing
if (foo.equals(m.get("x"))) { //will never throw an NPE because foo is never null
...
}
Note that your example isn't going to work in general because comparing non-primitive values with ==
only returns true if they refer to the same object instance. (Which in this case might even be true for very specific reasons but most of the time it isn't.)
Upvotes: 1