How to create read only collections in java?

Use the following code to create read only collections in Java.

List<String> strLst = new ArrayList<String>();
strLst.add("1");
strLst = Collections.unmodifiableList(strLst);
strLst.add("2");

In the above, when line number 4 is executed, it throws java.lang.UnsupportedOperationException.

This is because an unmodifiable List is retrieved at line number 3.

Interview Questions: 

Search