How should lists be cast to their conrecte implementations?

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

    It would throw a ClassCastException if you downcasted to ArrayList when in fact it was a LinkedList. Generally its never a good idea to downcast like this especially if you didn't write the code that returns the object you want to downcast. Plus if you are using 3rd party libs like this they might change what they return you as they improve their code. If you put downcasts like this in your code it might work today, but when you upgrade your libs it all of a sudden it breaks. And it breaks at runtime not compile time so you won't know its broken until you run it. This is an issue of you violating the contract the library has with you which only using a List interface.

    0 讨论(0)
  • 2021-01-15 01:21

    Why don't you do this:

    List<SomeObj> objs = getObjs();
    

    And then work with that list. If for some reason you really need a ArrayList, you can always do

    ArrayList<SomeObj> arrayList = new ArrayList<SomeObj>();
    arrayList.addAll(objs);
    

    And work with that. This is not very efficient though.

    0 讨论(0)
  • 2021-01-15 01:24

    You're correct. That is not a good idea. You need to use the interface form that it's returning.

    0 讨论(0)
提交回复
热议问题