How should lists be cast to their conrecte implementations?

前端 未结 9 689
小蘑菇
小蘑菇 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:13

    It's not a good idea because you don't know what implementation the method returns; if it's not an ArrayList, you'll get a ClassCastException. In fact, you should not be concerned with what exact implementation the method returns. Use the List interface instead.

    If, for some reason, you absolutely need an ArrayList, then create your own ArrayList and initialize it with the List returned by the method:

    ArrayList myOwnList = new ArrayList(getObjs());
    

    But don't do this, unless you absolutely need an ArrayList - because it's inefficient.

提交回复
热议问题