Friday, May 06, 2005

creating read-only views of collections inside a application

// create a list and add some items to it

List stringlist = new ArrayList();
stringlist.add("alpha");
stringlist.add("beta");
stringlist.add("gamma");

// create an unmodifiable view of the list

List rolist = Collections.unmodifiableList(stringlist);

// add to the original list (works OK)

stringlist.add("delta");

// add through the read-only view (gives an exception)

rolist.add("delta");

No comments: