Showing posts with label Collections-methods. Show all posts
Showing posts with label Collections-methods. Show all posts

Wednesday, 18 May 2011

Sorting an ArrayList in java

If the data in your ArrayList has a natural sorting order (ie, implements Comparable, as do String, Integer, ...), you can simply call the static Collections.sort() method. This is a stable, guaranteed n log n sort.
Collections.sort(yourArrayList);
If you want to choose a different sort criterion or your data doesn't implement xxxx, you will have to define a Comparator and pass that to the sort() method.
Collections.sort(yourArrayList, yourComparator);
Check out Collections for other useful utility methods.

Thursday, 31 March 2011

Creating read-only or unmodifiable collection in java

You can create a java collection which cannot be modified. These collections can be called read only collections or unmodifiable collections.

When we try to edit these read only collection we get UnsupportedOperationException.


Eg.
Read-only map can be obtained from unmodifiableMap function of collections:
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1,"apple");
map.put(2,"orange");
map.put(3,"banana");

// Create unmodifiable view
Map<Integer, String> readonlyMap = Collections.unmodifiableMap(map);

// This throws UnsupportedOperationException
readonlyMap.put(4,"clementine");

Methods by Collections class

The Collections class provides six factory methods, one for each of Collection, List, Map, Set, SortedMap, and SortedSet.

Collection unmodifiableCollection(Collection collection)
List unmodifiableList(List list)
Map unmodifiableMap(Map map)
Set unmodifiableSet(Set set)
SortedMap unmodifiableSortedMap(SortedMap map)
SortedSet unmodifiableSortedSet(SortedSet set)

You should set the collection with required values then pass it as value to the Collections’ respective method. Most important thing here is, just passing and setting it as unModifiableX is not enough. These methods will return you collection as read only. You need to overwrite your old collection with this new read only collection. If you don’t do that, using the reference of the old collection the values can be modified. Cool right!

The returned set will be serializable if the specified set is serializable. As mentioned earlier, if you attempt to modify a read-only collection it will throw an UnsupportedOperationException.