Delphi Clinic | C++Builder Gate | Training & Consultancy | Delphi Notes Weblog | Dr.Bob's Webshop |
|
Sorting using java.util.Array
In Java 2 we have got a new collections framework.
Before Java 2 we had to use something like a Vector class or an array to store multiple objects.
For a more sophisticated collections framework we could always use the JGL library included with JBuilder.
With the Java 2 Collection framework we have more options for storing sets of objects, but also we get a lot of utility methods to sort sets of object, even for the older arrays.
The java.util.Arrays is the class we have to use. Multiple static methods are defined in this class and can be used to sort and search in arrays. The sort() method accepts a lot of arrays as a parameter to be sorted. Basically we have three different possible method invocations:
Let's see how we can use the different sort() methods and what the effect is. First we define a simple String array with the names of all the contributors to this website:
String[] contributors = new String[] { "David", "Micha", "Arjan", "Bob", "Hubert", "Barry", "Arnim" };Then we can use this list of contributors to pass as a parameter to the Arrays.sort() method:
Arrays.sort(contributors);If we print the contents of the array we get the following result:
Arjan Arnim Barry Bob David Hubert Micha
Without any knowledge of sorting algorithms we can now easily sort objects!
We now take a look at the other sort() methods. We can for example only sort the first three items in the list of contributors:
Arrays.sort(contributors, 0, 3);And we get the following output:
Arjan David Micha Bob Hubert Barry Arnim
We notice that indeed only the first three items are sorted and the rest of the objects is left as is.
Let's create our own comparator object to define our own rules for sorting the list of objects. To create a comparator we only have to implement the java.util.Comparator interface for a class. In our little example we will create an anonymous comparator class, which will sort the list of contributors reverse:
Arrays.sort(contributors, new Comparator() { public int compare(Object o1, Object o2) { String s1 = o1.toString().toLowerCase(); String s2 = o2.toString().toLowerCase(); return s2.compareTo(s1); } });The output shows the list of contributors reverse sorted:
Micha Hubert David Bob Barry Arnim Arjan