Java Reference
In-Depth Information
3. Line 10 invokes the sort method of Collections . The sort method modifies list ,
rearranging the Character objects into their natural order, which is strictly based on
the order of their numeric Unicode values.
4. The for-each loop on line 11 displays the sorted list.
Suppose the program is executed with the following command:
java CharacterSorter soRTedChAractERs
The output is
A C E R R T a c d e h o r s s t
Notice that uppercase letters precede all lowercase letters because the numeric Unicode
values of uppercase letters appear before the lowercase letters.
Natural Ordering of Wrapper Classes and Strings
The exam objectives mention knowledge of the natural ordering of the primitive wrapper
classes and String . The natural ordering of the numeric classes Byte , Short , Integer ,
Long , Float , and Double matches their natural ordering in the number system, just as
expected.
As we saw in the CharacterSorter program, Character objects are naturally ordered
by their numeric Unicode values (which is not alphabetical because all uppercase letters
appear before all lowercase letters).
For Boolean objects, true is considered greater than false . For example, the following
statements output 1 :
Boolean b = true;
System.out.println(b.compareTo(false));
As we saw in the earlier section “The Comparable Interface,” the natural order of
String objects is lexicographical, meaning that the fi rst different character in two String
objects determines the ordering. See if you can determine the output of the following
statements:
String s1 = “hello”;
String s2 = “hEllo”;
String s3 = “hellothere”;
List<String> list = new ArrayList<String>();
list.add(s1);
list.add(s2);
Search WWH ::




Custom Search