Java Reference
In-Depth Information
list.add(s3);
Collections.sort(list);
for(String s : list) {
System.out.println(s);
}
All three
String
objects share the same fi rst character, so their second character
determines the ordering. Because
E
comes before
e
,
“hEllo”
comes before both
“hello”
and
“hellothere“
. Because
“hello”
and
“hellothere”
do not contain a different
character to determine their order,
“hello”
comes fi rst because it is the shorter
String
.
The output of the previous statements is
hEllo
hello
hellothere
Sorting a list using the natural ordering requires each element in the
List
object to
implement the
Comparable
interface and also that each element in the list be mutually
comparable. For example, the following code does not compile. Can you see why?
6. List<Object> items = new ArrayList<Object>();
7. items.add(“Java”);
8. items.add(new Integer(123));
9. Collections.sort(items);
Lines 6-8 are valid and compile fi ne. The compiler error occurs at line 9. Because the
Collections.sort
method uses a generic type of
<T extends Comparable<? super T>
,
only
List
objects whose generic type implements
Comparable
can be an argument for
the
sort
method. The
Object
class does not implement
Comparable
, so line 9 generates the
following compiler error:
MutuallyComparableDemo.java:9: cannot find symbol
symbol : method sort(java.util.List<java.lang.Object>)
location: class java.util.Collections
Collections.sort(items);
The compiler is complaining that it cannot fi nd a version of
sort
in
Collections
that
takes in a
List<Object>
. Java generics are working their magic in this example, enforcing
data type rules at compile time to avoid issues at runtime. If line 9 compiled successfully,
then invoking
sort
would cause the
String
object
“Java”
to be compared to the
Integer
object wrapping
123
, which would result in a
ClassCastException
at runtime because
“Java”
and
123
are not mutually comparable.
Search WWH ::
Custom Search