Let's say I have a Map<Integer, Boolean>
and I want to filter out all the integers that have a boolean-value of true
. Here's some code:
for (Map.Entry<Integer, Boolean> e : map.entrySet()){
if (e.getValue() == true){ // Unboxing here
// Do something useful...
}
}
In this code, the Boolean
-object is unboxed every time the if is executed (which might be a problem if the map is really large).
Now, the Boolean
-class offers constants (Boolean.TRUE
and Boolean.FALSE
), which represent the normal boolean values true
and false
as an already boxed version (right?). So using this code would avoid unboxing completely:
for (Map.Entry<Integer, Boolean> e : map.entrySet()){
if (e.getValue() == Boolean.TRUE){ // No Unboxing done (?)
// Do something useful...
}
}
Am I right about this assumption? Or is it even worse and both values are unboxed to be compared?
It will work if you used the primitive boolean
literals to add elements to your map.
When using primitive literals where a reference type is expected, the compiler will use Boolean#valueOf(..)
implemented as
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
to return a value of type Boolean
. So you will get the same two Boolean
objects every time.
If you instead added to the map with
new Boolean(true) // or new Boolean(false)
it will be a different reference, so comparison with ==
will fail.
This does seem like premature optimization.