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<SomeObj> getObjs() { ... }
I’m wondering if this is a good idea:
ArrayList<SomeObj> objs = (ArrayList<SomeObj>) getObjs();
If, for example, the concrete implementation of the List inside getObjs() is a LinkedList then wouldn’t there be some kind of type discrepancy?
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 fromArrayList.Also, if you do, you need to be really sure that the list returned is an
ArrayList. In this case, the promised contract ofgetObjs()is only that the return type is some kind ofList, so you shouldn’t assume anything else. Even if theListreturned now would beArrayList, there is nothing preventing the implementer ofgetObjs()to later change the type ofListreturned, which would then break your code.