Sorting a Collection


// sorting an array int[] myInts = {1,5,7,8,2,3}; Arrays.sort(myInts); // sorting a List List myList = new ArrayList(); myList.put(obj1); myList.put(obj2); Collections.sort(myList);



The Arrays class is a class in the java.util package that contains a bunch of static methods for manipulating arrays. The useful method here is the sort() method. The sort() method takes an array of objects or primitives along with optional from and to indexes. The from index, if passed, would specify the index of the first element to be sorted, and the to index would specify the index of the last element to be sorted. Primitives are sorted in ascending order. When using this method to sort objects, all the objects must implement the Comparable interface, or alternatively a Comparator object can be passed. In our phrase, we have an array of integers of type int. We pass this array to the Arrays.sort() method, and the array is sorted. It is important to point out that the actual array that is passed in is the array that is sorted and thus modified. A new sorted array is not returned. The sort() method has a void return type.

The Collections class is another class in the java.util package, which contains static methods that operate on other collection objects. The sort() method takes a List object as input and sorts the items in the list into ascending order, according to natural ordering of the elements. Similar to the sort() method in the Arrays object, all elements in the List passed into this method must implement the Comparable interface, or alternatively a Comparator object can be passed along with the List. The list passed into the sort() method is modified. In the second part of our phrase, we create an ArrayList object and use the Collections.sort() method to sort it. In this example, since no Comparator object was passed in, the objects obj1 and obj2 must have implemented the Comparable interface.

If the default sort order is not what you want, you can implement the Comparator interface to define your own sorting mechanism. The comparator that you define can then be passed as the second argument to the sort() method of either Collections or Arrays class.

In addition to the classes described, the Collections Framework contains classes that are inherently sorted such as the TReeSet and TReeMap. If you use these classes, the elements are automatically sorted when they are placed into the collection. For a treeSet, the elements are sorted in ascending order according to the Comparable interface or by the Comparator provided at creation time. For a treeMap, the elements are in ascending key order according to the Comparable interface or by the Comparator provided at creation time.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net