Java Data Structures - Contents
A D V E R T I S E M E N T
Wasn't the last section scary and a bit confusing?
If you said "yes," then you're not alone. Java implementers also think
so; that's why a lot of the sorting thingies are already built in! JDK 1.2 introduced the Collection
interface; using it, we can do all kinds of data structures effects like sorting and
searching. For example, to sort a Vector , all we need to do is call a sort()
method of the java.util.Collections class.
import java.io.*;
import java.util.*;
public class pJDKVectorSortingUp{
public static void main(String[] args){
Vector v = new Vector();
System.out.print("starting...\nadding:");
for(int i=0;i<10;i++){
Integer j = new Integer((int)(Math.random()*100));
v.addElement(j);
System.out.print(" " + j);
}
Collections.sort(v);
System.out.print("\nprinting:");
Enumeration enum = v.elements();
while(enum.hasMoreElements())
System.out.print(" "+(Integer)enum.nextElement());
System.out.println("\nDone ;-)");
}
}
See how simple it is? The output follows...
starting...
adding: 91 37 16 53 11 15 89 44 90 58
printing: 11 15 16 37 44 53 58 89 90 91
Done ;-)
All this is nice and useful, but what if you need
descending order, instead of the "default" accenting one? Guess what?,
the implementers of the language have though about that as well! We have a java.util.Comparator
interface. With this Comparator , we can specify our own compare function,
making it possible to sort in descending order (or any other way we want... i.e.: sorting
absolute values, etc.).
import java.io.*;
import java.util.*;
public class pJDKVectorSortingDown implements Comparator{
public int compare(Object o1,Object o2){
return -((Comparable)o1).compareTo(o2);
}
public static void main(String[] args){
Vector v = new Vector();
System.out.print("starting...\nadding:");
for(int i=0;i<10;i++){
Integer j = new Integer((int)(Math.random()*100));
v.addElement(j);
System.out.print(" " + j);
}
Collections.sort(v,new pJDKVectorSortingDown());
System.out.print("\nprinting:");
Enumeration enum = v.elements();
while(enum.hasMoreElements())
System.out.print(" "+(Integer)enum.nextElement());
System.out.println("\nDone ;-)");
}
}
As you can see, this time, we're sending a Comparator
object to the Collections.sort() method. This technique is really cool and
useful. The output from the above program follows:
starting...
adding: 9 96 58 64 13 99 91 55 51 95
printing: 99 96 95 91 64 58 55 51 13 9
Done ;-)
I suggest you go over all those JDK classes and
their methods. There is a LOT of useful stuff there. Now, say good bye to sorting for a
while; we're moving into something totally different; NOT!
Back to Table of Contents
A D V E R T I S E M E N T
|
Subscribe to SourceCodesWorld - Techies Talk |
|