How should lists be cast to their conrecte implementations?

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

提交回复
热议问题