make ArrayList Read only

后端 未结 4 1669
温柔的废话
温柔的废话 2020-12-05 09:30

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

相关标签:
4条回答
  • 2020-12-05 09:46

    Pass the ArrayList into Collections.unmodifiableList(). It returns an unmodifiable view of the specified list. Only use this returned List, and never the original ArrayList.

    0 讨论(0)
  • 2020-12-05 09:49

    Pass the collection object to its equivalent unmodifiable function of Collections class. The following code shows 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);
        }
    
    }
    

    same way you can create other collections unmodifiable as well

    • Collections.unmodifiableMap(map)
    • Collections.unmodifiableSet(set)
    0 讨论(0)
  • 2020-12-05 10:00

    Pass the list object to Collections.unmodifiableList(). See the example below.

    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.");
        }
    }
    
    0 讨论(0)
  • 2020-12-05 10:01

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

    Maybe it would be better to first populate an ArrayList with all of your information, and then convert the ArrayList into a final array when the Java program initializes.

    0 讨论(0)
提交回复
热议问题