Un Modifiable Wrapper Example Java Program


A wrapper class is a class that encapsulates types, so that those types can be used to create object instances and methods in another class that need those types. An UnModifiableWrapper is a wrapper which cannot be modified. It produces UnsupportedOperationException when tried to edit.



Un Modifiable Wrapper Example Program

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UnmodifiableWrappersExample {

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();

        list.add("Two Hundred");
        list.add("Three Hundred");
        list.add("Four Hundred");
        list.add("Five Hundred");

        System.out.println("Initial value of list : " + list);

        List<String> unModifiableList = Collections.unmodifiableList(list);
        System.out.println("Values of Unmodifiable list : " + unModifiableList);
        unModifiableList.add("Thousand");// Produces Exception
        System.out.println("After adding value 'Thousand' to list, the value is : " + unModifiableList);

Sample Output

Initial value of list : [Hundred, Two Hundred, Three Hundred, Four Hundred, Five Hundred]
Values of Unmodifiable list : [Hundred, Two Hundred, Three Hundred, Four Hundred, Five Hundred]
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
        at UnmodifiableWrappersExample.main(UnmodifiableWrappersExample.java:21)