Wednesday 3 April 2013

How to create read only List, Map and Set in Java

// creating List in Java
List<String>  names= new ArrayList<String>();

// initializing List in Java
names.add("Raja");
names.add("Ramesh");
names.add("Ramu");

Set<String> readOnlySet = new HashSet<String>(names);

 //Set is not yet read-only you can still add elements into Set
readOnlySet.add("Ravi");
//making Set readonly in Java - no add remove or set operation permitted
readOnlySet = Collections.unmodifiableSet(readOnlySet);

//trying to add element in read only Set - java.lang.UnSupportedOperationException
readOnlySet.add("You can not add element in read Only Set");

//trying to remove element from read only set
readOnlySet.remove("Ramu");

//you can not remove elements from read only Set

Map<StringString> agesmap = new HashMap<StringString>();
agesmap.put("raja", "24");

//Map is not read only yet, you can still add entries into
agesmap.put("ramesh", "22");

System.out.println("Map in Java before making read only: " + contries);

//Making Map read only in Java
Map readOnlyMap = Collections.unmodifiableMap(agesmap);

//you can not put a new entry in read only Map in Java
readOnlyMap.put("ra", "33"); //java.lang.UnSupportedOperation 

//you can not remove keys from read only Map in Java
readOnlyMap.remove("raja"); //java.lang.UnSupportedOperation

No comments:

Post a Comment