首页 > 其他 > 详细

将集合设置为只读

时间:2014-01-23 17:24:52      阅读:414      评论:0      收藏:0      [点我收藏+]

  有时候,我们希望一个集合只能读,不能写。像.NET语言就提供了只读的集合,可惜Java中却没有。

    还好集合工具类Collections为我们提供了静态工厂方法来生成只读集合,包括Collection,List,Map,Set,SortedMap和SortedSet,下面给出了各自的方法签名。

 

  • Collection unmodifiableCollection(Collection collection)
  • List unmodifiableList(List list)
  • Map unmodifiableMap(Map map)
  • Set unmodifiableSet(Set set)
  • SortedMap unmodifiableSortedMap(SortedMap map)
  • SortedSet unmodifiableSortedSet(SortedSet set)

    简单的例子:

bubuko.com,布布扣
public static void main(String[] args) {  
      
    List<String> fruits = Arrays.asList(new String[]{"りんご","スイカ","バナナ","葡萄"});  
      
    List<String> list = new ArrayList<String>(fruits);  
      
    list = Collections.unmodifiableList(list);      //覆盖 list的引用。  
      
    try{  
        list.add("変な物");  
    }catch(UnsupportedOperationException usoe){  
        usoe.printStackTrace();  
        System.exit(1);  
    }  
      
}  
bubuko.com,布布扣

    试图往可读集合中添加元素,将会抛出UnSupportedOperationException异常。

 

    注意到list对象引用被覆盖,如果list未被覆盖,那么在list的作用域内,list仍然可以写,而非只读。

将集合设置为只读

原文:http://www.cnblogs.com/ytfcz/p/3530774.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!