I'm new to Java, and I'm trying to figure out one thing about generics.
If I declare a method like
public <T> List<T> toList(final T... arr) { ... }
Can I return both ArrayList
and LinkedList
?
Or for example, if I have declare a method like
public <T> T[] toArray(final List<T> l) { ... }
Can I pass both ArrayList
and LinkedList
as argument and it'll works good?
If this is right, does it works with all objects too? So, if I create a class and I extend it more times, can I use the top class as arg of method, but the pass its subclasses when I call it?
CodePudding user response:
It's not about generics only. You can assign any object to a variable of its parent class.
Object o = 5; // It's valid
If you pass a LinkedList
or ArrayList
to the toArray()
method, it doesn't matter. It will be automatically converted to List
. Similarly, if you return a LinkedList
from the toArray()
method, it doesn't matter. It will be converted to List.
But one thing to keep in mind is if you pass a LinkedList
, it will get converted to List
and you will be able to use only the methods of the List
interface.
List list = new LinkedList();
list.addFirst(1); // Invalid