make ArrayList Read only

后端 未结 4 1674
温柔的废话
温柔的废话 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: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 objList = new ArrayList();
            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)

提交回复
热议问题