Collections Java collection of analysis

  Collections tools located next java.util package, is a more commonly used tools, about the tools, introduces its pit encountered in the course! ! !

  

  【accident scene】

  In the actual project development process, on the basis of previous code, to add to a collection of elements, java.lang.UnsupportedOperationException throw an exception, for a List collection, a common additive elements on the error, it is hard to understand.

 

  [Analysis] accident

  When initializing a common set of List, more common is the List list = new ArrayList (); we are free to add and remove the collection operation, but use the collection is the previous code initializes List emptyList = Collections.EMPTY_LIST; relatively new, so-called existence that is reasonable, look at the source code! ! !

    First of all the EMPTY_LIST initialized when a EmptyList new class that inherits from EmptyList AbstractList class, in a blog post https://www.cnblogs.com/Demrystv/p/11608109.html already mentioned this class, can not which was add or remove methods, because it is in the source code will throw an exception, see here, why add or remove elements throw an exception EMPTY_LIST solved.

    

    

    

 

  [Reflect] accident

  Collections.EMPTY_LIST返回的是一个空的List。在某个函数中返回的List可能为空,采用常规的ArrayList等我们需要进行是否为null 的判断,但是采用这个Collections.EMPTY_LIST可以减少判断的步骤。相比于ArrayList,这个在初始化时占用较少的资源,所以这就是Collections.EMPTY_LIST的优势。但是,需要注意的是我们在后续不能对其add或者 remove操作,否则就会抛异常。同理,EMPTY_MAP和EMPTY_SET在使用时也要多加注意。

 

Guess you like

Origin www.cnblogs.com/Demrystv/p/11608296.html