Read Only Collections

Last modified on August 1st, 2014 by Joe.

I do build crazy buildings using my collection of Lego blocks. My 11 months old kid Ben curiously stares at me build it. He always wishes to get hold of it. After I complete the building when I give that to his hand, you know what the first thing he does.

Lego Blocks

Modify the building blocks. Though I wish them to be intact forever Lego buildings are built to be modified.

But this is not the case in programming. You create a java collection and store objects in it. Then there are scenarios where you want them not be modified. Obsessed with file system terminology Java guys have named it as read only collections.

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.

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!");
}
}
}

Comments on "Read Only Collections"

  1. Dipraj says:

    Thanks, you are exposing new feature of Collection framework.

  2. Mayank says:

    Your second para was really super cool.
    Gr8 catch Man.
    Cheers, Mayank

  3. Anonymous says:

    very clear and simple document.easy to understand..thank u.

  4. Anonymous says:

    how to utilize collections?it would be more useful if u have used more examples.otherwise add examples as a new menu…

  5. Anonymous says:

    Thanks, you are exposing new feature of Collection framework. I really thanks to you

  6. Niket Patel says:

    hi i am getting collection from entity bean
    and them i am going to remove element from that collection it gives the error as below
    javax.ejb.EJBException: This collection is a read-only snapshot
    please help me regarding this.
    Thanks

  7. Nandan says:

    Thank you very much Joe…:)

  8. Shivkant Pandey says:

    Thanks for the article. A new thing which I studied today.

  9. ashish says:

    Joe ,i have a question- how does set check that a duplicate object is being added to it?

  10. Anonymous says:

    thank u Joe,its very nice collection and easy to understand;

  11. Pragadeesh.N says:

    thank u Joe,its very nice collection and easy to understand;

  12. Pragadeesh.N says:

    how to delete the duplicate element using collections.i want answer.

  13. ravikumar says:

    Thanks Joe… Your explanation is good…

  14. Snehal Masne says:

    Thanks for the article. A new thing which I studied today. Keep it up Joe!

    Regards,
    Snehal Masne

  15. SAURAV SAVARN says:

    GOOD ONE

  16. Anonymous says:

    super good one thanks

  17. Mallu says:

    Thank you.. can you get some OCJP dumps..

  18. Anonymous says:

    Thanks, useful information.

  19. xxx says:

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

    Map is not a collection

  20. dilip says:

    This is one of the best para for me It is really helpful for me

    Thanks

  21. siddhartha says:

    Please post Interview Question regarding these topics individually

    concurrency
    executors
    collections
    hashmap
    internal implementation of each of these collections
    blocking queue
    core java design patterns
    singleton
    observer 1 case study 1 written test
    linked list implementation
    multithreading program
    to implement join using thread join method
    deadlock
    mutithreading and concurrency
    strings, inheritence, overriding
    servlets
    concurrency in servlets
    hibernate – basics only
    webservices – soap and rest – where to use
    project related questions.

  22. suganya says:

    Hi Joe

    Very good article. Can u come up with more collection article.

    Thanks
    Suganya

Comments are closed for "Read Only Collections".