How should lists be cast to their conrecte implementations?

前端 未结 9 695
小蘑菇
小蘑菇 2021-01-15 00:49

Let\'s suppose I\'m using a library for which I don\'t know the source code. It has a method that returns a List, like so:

public List getObjs         


        
9条回答
  •  遥遥无期
    2021-01-15 01:20

    No, it is not a good idea. You should always use the interface (List) to declare your list variable unless you for some reason need specific behaviour from ArrayList.
    Also, if you do, you need to be really sure that the list returned is an ArrayList. In this case, the promised contract of getObjs() is only that the return type is some kind of List, so you shouldn't assume anything else. Even if the List returned now would be ArrayList , there is nothing preventing the implementer of getObjs() to later change the type of List returned, which would then break your code.

提交回复
热议问题