Make ArrayList Read Only

In Java, how can you make an ArrayList read-only (so that no one can add elements, edit or delete elements) after initialization?

+42
java collections arraylist java-ee
Mar 10 '10 at 18:08
source share
5 answers

Pass the ArrayList to Collections.unmodifiableList () . It returns an unmodifiable representation of the specified list. Use this returned list and never use the original ArrayList.

+84
Mar 10 '10 at 18:09
source share

Pass the list object to Collections.unmodifiableList (). The following is an example of an example.

  import java.util.*; public class CollDemo { public static void main(String[] argv) throws Exception { List stuff = Arrays.asList(new String[] { "a", "b" }); List list = new ArrayList(stuff); list = Collections.unmodifiableList(list); Set set = new HashSet(stuff); set = Collections.unmodifiableSet(set); Map map = new HashMap(); map = Collections.unmodifiableMap(map); System.out.println("Collection is read-only now."); } } 
+2
Jun 29 '15 at 8:57
source share

Are you sure you want to use ArrayList in this case?

It might be better to populate the ArrayList with all your information first, and then convert the ArrayList to a finite array when the Java program initializes

0
Mar 10 '10 at 19:27
source share

Check the Google Collections , and for your needs look at the ImmutableList. But all there is to see.

0
Mar 10 '10 at 19:33
source share

Pass the collection object to its equivalent non-modifiable function in the Collections class, the following code shows the use of unmodifiableList

 import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Temp { public static void main(String[] args) { List<Integer> objList = new ArrayList<Integer>(); objList.add(4); objList.add(5); objList.add(6); objList.add(7); objList = Collections.unmodifiableList(objList); System.out.println("List contents " + objList); try { objList.add(9); } catch(UnsupportedOperationException e) { e.printStackTrace(); System.out.println("Exception occured"); } System.out.println("List contents " + objList); } } 

just like you can create other collections that are not modifiable,

  • Collections.unmodifiableMap (map);
  • Collections.unmodifiableSet (set);
0
Mar 14 '16 at 10:15
source share



All Articles