3 ms·
The form: Boolean b = Boolean.valueOf(true); Is slightly more efficient than the subjectively uglier: Boolean b = new Boolean(true); So couple of notes o
by exabrial 7y ago
The form:
Boolean b = Boolean.valueOf(true);
Is slightly more efficient than the subjectively uglier:
Boolean b = new Boolean(true);
So couple of notes on that. The "new" operator is cheap, but still involves an allocation. Oddly enough, one of the strangest bugs I found back in the day was:
Boolean a = new Boolean(true);
Boolean b = new Boolean(true);
System.out.println(a == b);
false
But with objects and wrapper types, the .equals() method is the correct way to compare two objects.
- stygiansonic 7y agoIn my opinion this behaviour shouldn’t be considered strange - “new” always means instantiation of a new object and the “==“ operator for objects always checks for object identity. Since both operands are objects, the above would apply. This is another reason to avoid boxed primitive whenever possible.
- exabrial 7y agoAgree. The "new" operator in my case was hidden deep inside a corporate framework where the guy that invented it had left a long time ago. Quite an adventure down the rabbit hole to figure that out! Boxed primitives are useful when working with systems and languages where "null" is a concept. Take for example, interacting with a database where you have a boolean column that has true/false/null. That translates well to boxed primitive types.