== vs. .equals()
For all reference types, including Integer etc., the meaning
of == and != is
equality of pointer values, i.e. same data address in memory.
Rule: To test equality of the contents or value of a reference type,
always use .equals().
Rule: To compare against null, use == or != .
Rule: To make an Integer from an int, either use:
- Integer myInteger = (Integer) myint;
(casting)
- Integer myInteger = myint;
(auto-boxing)
- Integer myInteger = Integer.valueOf(myint)
These can save storage:
- new Integer() always makes a new box, costing 16 bytes
and (eventually) garbage collection.
- Integer.valueOf() will reuse a value in the Integer
cache if possible, costing 0 bytes.
Contents
Page-10
Prev
Next
Page+10
Index