2

我有一个函数f,它获取 a 的子列表LinkedList并将其传递给g,它也需要 a LinkedList

public static <T> void g(LinkedList<T> l) {
}

public static <T> void f() {
    LinkedList<T> l = new LinkedList<T>();
    ...
    LinkedList<T> l2 = l.subList(i,j);
    ...
    g(l2);
}

但这不会编译,因为显然LinkedList.subList返回List而不是LinkedList. 所以我必须把它改成这样:

LinkedList<T> l2 = (LinkedList<T>)l.subList(i,j);

为什么?

4

5 回答 5

5

subList is defined in the List interface and returns a List. And if you check the implementation in LinkedList, which is actually in one of the parent classes (AbstractList), you will see that it does not return a LinkedList but a SubList and your cast will throw an exception.

Unless you use methods specific to LinkedList, the easiest way to fix this would be to change g to:

public static <T> void g(List<T> l) {
于 2013-04-17T19:02:05.877 回答
0

if g() doesn't use the method of LinkedList but only the List interface is preferable to define g() as follow:

public static <T> void g( List<T> l ) {
}

and the main becomes:

public static <T> void f() {
    List<T> l = new LinkedList<T>();
    ...
    List<T> l2 = l.subList(i,j);
    ...
    g(l2);
}

For a justification, please consult this post.

于 2013-04-17T19:02:22.690 回答
0

该方法在由 实现的接口中sublist声明。接口中方法的签名是:ListLinkedListsublistList

 List<E> subList(int fromIndex, int toIndex)

因此,每当您从LinkedList类中调用此方法时,对象将为LinkedList,但方法的返回类型为List,因此将以 的形式给出List。但是,您可以将变量转换为LinkedList并使用它。

于 2013-04-17T19:04:46.257 回答
0

您不能实例化“对象”这样的列表。List 是一个接口,而不是一个具体的类。接口只是一个类可以实现的一组功能;实例化一个接口没有任何意义。

希望能帮助到你。

克莱门西奥·莫拉莱斯·卢卡斯。

于 2014-10-15T13:17:15.340 回答
-1

Java wants as much polymorphism as you can get, so subList returns List, and you have to cast it to what you want.

于 2013-04-17T19:02:49.637 回答