首页 > 解决方案 > Arguments of methods

问题描述

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?

标签: javagenerics

解决方案


这不仅仅是关于泛型。您可以将任何对象分配给其父类的变量。

Object o = 5;    // It's valid

如果您将LinkedListor传递ArrayList给该toArray()方法,则无关紧要。它将自动转换为List. 同样,如果您LinkedListtoArray()方法返回 a ,也没关系。它将被转换为List.

但要记住的一件事是,如果您传递 a LinkedList,它将被转换为List并且您将只能使用List接口的方法。

List list = new LinkedList();
list.addFirst(1);              // Invalid

推荐阅读