Since in Java, generics usually operate on Object under the hood, I was curious if emplacing such values incurs more overhead than placing an already existing object.
Consider having a Map<String, Object> that can contain arbitrary meta information. You want to put a flag kinda entry there – if it is present, the flag is enabled.
So you have something like this:
static final String MY_FLAG_NAME = "name";
Map<String, Object> myMap;
Now I wonder if there is a difference in between these three implementations of setting the flat:
myMap.put(MY_FLAG_NAME, true)(falseto disable)myMap.put(MY_FLAG_NAME, null)(we can usecontainsKey, but this looks dirty to me)myMap.put(MY_FLAG_NAME, MY_FLAG_NAME)(string is already allocated, and we can use""for disable)
My question here is if this will force at some point some kind of new Boolean() under the hood, or if it does not matter whether I put a string or a boolean. I never really got to understood how precisely Java handles the boolean/Boolean difference in generics, same for other primitive types.
This code would be called a lot, but I don’t have enough Java knowledge to make a trustworthy performance test.
>Solution :
Boxing constant booleans (like the literals true and false) does not create arbitrarily many new objects. The Java Language Specification says:
If the value p being boxed is the result of evaluating a constant expression (§15.29) of type
boolean, […], and the result istrue,false, […], then letaandbbe the results of any two boxing conversions ofp. It is always the case thata == b.
If it is not a constant boolean expression (e.g. someString.length() == 5), the language specification doesn’t guarantee boxing to produce the same object, but I think any reasonable implementation would implement boolean boxing as calling Boolean.valueof(boolean), which does not create arbitrarily many new Boolean objects. It just returns the static final fields Boolean.TRUE and Boolean.FALSE. Of course, new Boolean objects will be created when the TRUE and FALSE fields are initialised, but no other Boolean objects will be created if you only use Boolean.valueOf.
Returns a
Booleaninstance representing the specified boolean value. If the specified boolean value istrue, this method returnsBoolean.TRUE; if it isfalse, this method returnsBoolean.FALSE.