Collection Framework - Utility classes

Collection framework provides 2 utility classes : Collections and Arrays

1. Collections

The  default implementation of ArrayList is non-synchronized. What if we wanted a synchronized version of an ArrayList.

Collections class provides a method for the same as below ;

ArrayList arrayList = new ArrayList();
List synchronizedArrayList = Collections.synchronizedList(arrayList);

The same thing holds true for sets and maps as well. Collections class provides methods :
synchronizedSet() and synchronizedMap() respectively.

Collection class also provides for implementation of sorting for collection classes which do not come with default sort mechanisms such as ArrayList.

ArrayList arrayList = new ArrayList();
arrayList.add(25);
arrayList.add(15);
arrayList.add(0)
ArrayList.add(100);

Collections.sort(arrayList); //sorts in the natural sorting order.
Collections.sort(arrayList, descendingComparator); //define your comparator and use it for sorting.

There are many more methods that Collections provides. An example for the same can be found here

2. Arrays
Similar to Collections class, Arrays class provides utility methods.

You can do sorting, searching, reversing elements, etc.  Please try it yourself, it is similar to Collections so i have not created an example for that.

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures