Pass the collection object to its equivalent non-modifiable function in the Collections class, the following code shows the use of unmodifiableList
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Temp { public static void main(String[] args) { List<Integer> objList = new ArrayList<Integer>(); objList.add(4); objList.add(5); objList.add(6); objList.add(7); objList = Collections.unmodifiableList(objList); System.out.println("List contents " + objList); try { objList.add(9); } catch(UnsupportedOperationException e) { e.printStackTrace(); System.out.println("Exception occured"); } System.out.println("List contents " + objList); } }
just like you can create other collections that are not modifiable,
- Collections.unmodifiableMap (map);
- Collections.unmodifiableSet (set);
Amar Magar Mar 14 '16 at 10:15 2016-03-14 10:15
source share