top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to you make Collections readOnly in Java?

0 votes
388 views
How to you make Collections readOnly in Java?
posted Apr 4, 2016 by Naveen Kumar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

By default some of the languages like dot net provide read only collections. But in Java there are no such things. This is not a special type of collection it is an additional facility provided to change the usual collections as read only.

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. If you attempt to modify a read-only collection it will throw an UnsupportedOperationException.

Example source code for java read only collections

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

// example program to demonstrate the read-only collection in java
public class ReadOnlyCollections {

public static void main(String args[]) {

// creating a list
List godList = Arrays
.asList(new String[] { "Donald", "Dennis", "Ken" });

// making a read-only list
List list = new ArrayList(godList);
list = Collections.unmodifiableList(list);

// checking the reference in a read-only set
Set set = new HashSet(godList);
Collections.unmodifiableSet(set);

// the following statement allows to modify the above set as the
// reference is pointing to the original collection therefore it is not
// read-only
set.add("Alan");

// making a read-only map and try to modify it
Map godMap = new HashMap();
godMap.put("TAOCP", "Donald");
godMap.put("C", "Dennis");

godMap = Collections.unmodifiableMap(godMap);

try {
// modifying the read-only map to check what happens
godMap.put("Unix", "Ken");
} catch (UnsupportedOperationException e) {
System.out.println("You cannot modify a read only collection!");
}
}
}
answer Apr 4, 2016 by Karthick.c
...