| Author |
How do you avoid an ArrayList object from being modified, i.e. avoid adding and deleting its content
|
Anjali Lamba
Greenhorn
Joined: Feb 02, 2011
Posts: 11
|
|
|
How do you avoid an ArrayList object from being modified, i.e. avoid adding and deleting its content
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32611
|
|
|
Go through the java.util.Collections class, where you will find methods allowing you to make a read-only copy of Lists, etc.
|
 |
Javin Paul
Ranch Hand
Joined: Oct 15, 2010
Posts: 276
|
|
Use following methods:
unmodifiableSet -- for getting unmodifiable version of Set
unmodifiableMap
unmodifiableList
etc.
|
http://javarevisited.blogspot.com - java classpath - Java67 - java hashmap - java logging tips java interview questions Java Enum Tutorial
|
 |
vinayak jog
Ranch Hand
Joined: Apr 01, 2011
Posts: 76
|
|
ArrayList al = new ArrayList();
al.add("string");
al =(ArrayList)Collections.unmodifiableCollection(al);
|
 |
Harsha Smith
Ranch Hand
Joined: Jul 18, 2011
Posts: 287
|
|
wrong answer. throws class cast exception
|
 |
vinayak jog
Ranch Hand
Joined: Apr 01, 2011
Posts: 76
|
|
Harsha Smith wrote:
wrong answer. throws class cast exception
List<String> al = new ArrayList<String>();
al.add("hello world");
al =(List)Collections.unmodifiableList(al);
System.out.println(al.get(0));
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24044
|
|
vinayak jog wrote:
Better -- although the cast at line 3 is redundant.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Campbell Ritchie wrote:Go through the java.util.Collections class, where you will find methods allowing you to make a read-only copy of Lists, etc.
Not a copy - a view. A copy implies that the data is copied and that modifying the original will not affect the copy. A view implies that the data is not copied and changes in the original will be seen in the view.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32611
|
|
Good point, Rob. One needs to be precise.
Note that the unmodifiable method returns a view, but the original List is still usually extant, and that can be modified.
|
 |
 |
|
|
subject: How do you avoid an ArrayList object from being modified, i.e. avoid adding and deleting its content
|
|
|