Tuesday, September 27, 2011
Comparable example
http://tim.oreilly.com/pub/a/onjava/2003/03/12/java_comp.html
Making Java Objects Comparable
by Budi Kurniawan
03/12/2003
In real life, objects are often comparable. For example, Dad's car is more expensive than Mom's, this dictionary is thicker than those books, Granny is older than Auntie Mollie (well, yeah, living objects, too, are comparable), and so forth. In writing object-oriented programs, there are often needs to compare instances of the same class. And once instances are comparable, they can be sorted. As an example, given two Employees, you may want to know which one has stayed in the organization longer. Or, in a search method for Person instances with a first name of Larry, you may want to display search results sorted by age. This article teaches you how to design your class to make its instances comparable by using the java.lang.Comparable and java.util.Comparator interfaces and presents three examples that illustrate both interfaces.
Most Java programmers know how to sort the elements of a String array by using the sort method of java.util.Arrays. For String instances in an ArrayList, you can sort them with the sort method of the java.util.Collections class. The code in Listing 1 shows how to use Arrays.sort to order String instances.
Listing 1: Sorting String Instances Using Arrays.sort
import java.util.Arrays;
.
.
.
String animals[] = new String[4];
animals[0] = "snake";
animals[1] = "kangaroo";
animals[2] = "wombat";
animals[3] = "bird";
for (int i=0; i<4; i++) {
System.out.println("animal " + i + " : " + animals[i]);
}
Arrays.sort(animals);
for (int i=0; i<4; i++) {
System.out.println("animal " + i + " : " + animals[i]);
}
If you run the program, the first for loop gives you the name of animals as follows:
animal 0 : snake
animal 1 : kangaroo
animal 2 : wombat
animal 3 : bird
And, the second for loop prints the animals sorted alphabetically.
animal 0 : bird
animal 1 : kangaroo
animal 2 : snake
animal 3 : wombat
With the java.util.Collections class's sort method, you can sort String instances in an ArrayList, as shown in Listing 2.
Listing 2: Sorting String Instances Using Collections.sort
import java.util.ArrayList;
import java.util.Collections;
.
.
.
ArrayList insects = new ArrayList();
insects.add("mosquito");
insects.add("butterfly");
insects.add("dragonfly");
insects.add("fly");
int size = insects.size();
for (int i=0; i
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment