Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Apr 23, 2001

Making a Read-only Collection


The Collections class provides static APIs to generate read-only or unmodifiable collections, lists, sets, or maps from specified entities. For instance, if you are sure that the ArrayList you've made should not be modified, you can generate a read-only list from it using the following:
 
  ArrayList list = new ArrayList();
  list.add("first");
  ...
  List readOnlyList = Collections.unmodifiableList(list);

It's important to discard the previous reference to the modifiable object. In the above example, we can still alter the list using the "list" variable. Since this defies the purpose of generating an unmodifiable list, and one should not do this. Any attempt to modify such a read-only object would result in an UnsupportedOperationException.
Shantanu Garg
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date