Thursday, March 5, 2009

Collections class

java.util.Collections :
This is the class contains several utility methods for searching and sorting for list implemented classes. These methods are applicable only for List Implemented classes.All the methods of this class are static
Sorting a list:
The collections class contains the following methods to perform sorting
static void sort(List list) //sorts the given list by the natural sorting order
static void sort(List list,Comparator c) //sorts the elements of list according to the sorting order specified by the Comparator

  • if list contains any null values then the sort() method throws NullPointerException

Collections class Demo Program:
import java.util.*;
public class SortingDemo {
public static void main(String [] args ) {
List l=new ArrayList();
l.add(“Z”);
ladd(“A”);
l.add(“H”);
l.add(‘E’);

l.add(“O”);
l.add(“B”);
l.add(‘F’);
l.add(“Y”);

System.out.println(“The List Before Sorting”+l);
Collections.sort(l);
System.out.println(“The List After Sorting”+l);
}
}

The above list is sorted according to the ascending order.to sort elements of an list according to the descending order we go for our own comparator
Sorting According To The Descending Order:
Collections.sort(l,new MyComparator());
class MyComparator implements Comparator {
public int comparator(Object o1,Object o2 ) {
String s1=(String)o1;
String s2=(String)o2;
S2.comareTo(s1);
}
}

Searching elements:
Collections class contains the following the methods for searching
binarySearch(List l, Object o) //if the object is present in the list then it will return the index of the list.otherwise it will return the insertion point
binarySearch(List l,Object o,Comparator c). // our own searching

Example:
import java.util.*;
public class SearchingDemo {
public static void main(String [] args ) {
List l=new ArrayList();
l.add(“Z”);
ladd(“A”);
l.add(“H”);
l.add(‘E’);

l.add(“O”);
l.add(“B”);
l.add(‘F’);
l.add(“Y”);

Collections.sort(l);
System.out.println(Collections.binarySearch(l,”A”));
System.out.println(Collections.binarySearch(l,”S”));
}
}

Reversing A List:
Collections class contains the following method to perform the revers operation
Static void reverse()

Demo Program:
import java.util.*;
public class ReverseDemo {
public static void main(String [] args ) {
List l=new ArrayList();
l.add(“Z”);
l.add(“A”);
l.add(“H”);
l.add(‘E’);

l.add(“O”);
l.add(“B”);
l.add(‘F’);
l.add(“Y”);

System.out.println(“The List”+l);
Collections.reverse(l);
System.out.println(“The Reversed List”+l);
}
}

0 comments:

Post a Comment