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
The reason why it returns a List
is so that you don't have to care what it is underlying that interface.
The List
interface simply declares the contract the object has to satisfy, and how you query it. The library author is at liberty in the future to pick an ArrayList
,a LinkedList
, or maybe a LazyDatabasePopulatedList
. In fact you may get a different implementation at runtime depending on how the providing class has been implemented.
So long as you have a contract to adhere to, this buys you a lot of freedom. There's a lot to be said for only talking and providing interfaces, and dealing with concrete classes as little as possible.
Cast to the return type defined by the API you are calling.
If it says it returns a List<SomeObj>
, then that is. Don't try to retrieve the underlying type, because:
a) It can vary with new versions (or even between calls)
b) You do not need to know the implementing class for anything.
If you need an ArrayList, then do new ArrayList<SomeObject)(getObjs());
The whole point of using interfaces (List) is to hide implementation details. Why do you want to cast it to specific implementation?
You should always use the interface in place of the Handle
. That is the whole point of OOP
Languages so that you can switch between any implementation later.
If you are casting to any concrete class, the compiler will warn you about a possibility of Cast
Exception that may occur. You can use SuppressWarning
if you are very much sure about the type.
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<SomeObj> myOwnList = new ArrayList(getObjs());
But don't do this, unless you absolutely need an ArrayList
- because it's inefficient.
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.