make ArrayList Read only

后端 未结 4 1670
温柔的废话
温柔的废话 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 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.");
        }
    }
    

提交回复
热议问题