Java Reference
In-Depth Information
Continued from previous page
It's difficult to know exactly what this code will do. If you assume that
ArrayList<Integer> is “almost” like an ArrayList<int> , you'd probably think
that the code would print the message that the two values are equal. In fact, there is
no guarantee as to what it will do. In the current version of Java, it prints the
message “unequal.”
Remember that testing for object equality is not as simple as testing for equal-
ity of primitive data. Two String s might store the same text but might not be the
same object, which is why we call the equals method to compare String s. The
same principle applies here: The two list elements might store the same int
but might not be the same object. The code prints “unequal” in the current
release of Java because the program creates two different Integer objects that
each store the value 420 . However, to add to the confusion, if we change the
value from 420 to 42 , the program will print that the two values are equal.
The Java Language Specification guarantees that this code will work for any
value of n between -128 and 127 , but it provides no guarantee as to how the
code will behave for other values of n . For those other values, it could print
either message, and this might change from one implementation of Java to
another. It might be that in the next version of Java released, the code will print
“equal” for 420 but not for a value like 420000 .
Some people have argued that because boxing and unboxing cover up what is
happening underneath, it is better not to use them at all. Boxing and unboxing
don't necessarily simplify anything if they work only “sometimes,” because you
have to be able to understand the cases in which they don't work.
Natural Ordering and compareTo
We are all familiar with many kinds of data that can be sorted. For example, we are
used to putting numbers in order from lowest to highest or alphabetizing lists of
names. We describe types that can be sorted as having a natural ordering of values.
To have such an ordering of values, a type needs to have a well-defined comparison
function that indicates the relationship between any pair of values.
Comparison Function
A well-defined procedure for deciding, given a pair of values, the relative
order of the two values (less than, equal to, or greater than).
Natural Ordering
The order imposed on a type by its comparison function.
 
Search WWH ::




Custom Search