Java Reference
In-Depth Information
This program produces the following output:
before sort, words = [four, score, and, seven, years, ago]
after sort, words = [ago, and, four, score, seven, years]
In Chapter 13 we will explore how this sorting method actually works. For now we
are simply going to be clients of the method without worrying about how it works.
If you try to make a similar call to an ArrayList<Point> , you will find that the
program does not compile. Why is it possible to sort a list of String objects but not a
list of Point objects? The answer is that the String class implements the Comparable
interface, while the Point class does not. In this section we will explore the details of
the Comparable interface and explain how to write classes that implement it.
Did You Know?
Controversy over Boxing and Unboxing
Not all software developers are happy with Sun's decision to add boxing and unbox-
ing to the Java language. The ability to manipulate an ArrayList<Integer>
almost as if it were an ArrayList<int> can simplify code, and everyone agrees
that simplification is good. The disagreement comes from the fact that it is
almost like an ArrayList<int> . Some argue that “almost” isn't good enough.
Because it comes close, programmers are likely to use it and eventually come to
count on it. That can prove disastrous when “almost” isn't “always.”
As an analogy, suppose someone told you that you could use a device that is
almost like a potholder to pick up hot objects. In most cases, it will protect your
hand from heat. So you start using it, and while you might be nervous at first,
you soon find that it seems to work just fine. And then one day you pick up a
new object and you get burned. You can think of similar analogies with aircraft
landing gear that almost works or vests that are almost bulletproof.
For a programming example, consider the following code:
int n = 420;
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(n);
list.add(n);
if (list.get(0) == list.get(1)) {
System.out.println("equal");
} else {
System.out.println("unequal");
}
Continued on next page
 
Search WWH ::




Custom Search