Collections class in Java
The java.util.Collections class contains a number of static methods operating on various collections.These methods take any collection member as argument and returns any (processed) collection member. If the collection object giving is null , thenNullPointerException will be thrown.
Now , let us see the applicability of Collection class with an example.As we already mentioned , Collection class is having a number of static methods.It is not possible to discuss all those methods here . Let us consider the sort() method as an example . Collections.sort() takes a List object and then sorts it.The order of sorting depends on the Comparable or Comparator instance. Here we are discussing Comparator.Our code creates an ArrayList object.Few String values are adding to it. Then sorting them in ascending order(sorting order depends on the Comparator instance.See more details about Comparable & Comparator).
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class CollectionsSample { private List list = null; public CollectionsSample() { list = new ArrayList(); } public void addItems() { list.add("Kerala"); list.add("TN"); list.add("AP"); list.add("Delhi"); list.add("MH"); } public void sortItems() { Comparator comp = new Comparator() { public int compare(String s1, String s2) { return s1.compareTo(s2); } ; }; Collections.sort(list, comp); } public void displayItems() { for (String item : list) { System.out.println(item); } } public static void main(String[] args) { CollectionsSample sample = new CollectionsSample(); sample.addItems(); System.out.println("Unsorted list is :"); sample.displayItems(); sample.sortItems(); System.out.println("Sorted List is :"); sample.displayItems(); } }
The working of Collections.sort() can be observed here.
Output
Unsorted list is :
Kerala
TN
AP
Delhi
MH
Sorted List is :
AP
Delhi
Kerala
MH
TN