简体   繁体   English

如何在Java中使用泛型类的超级类型?

[英]How do I use the super type of generic class in Java?

In my code I have a number of ArrayLists that are passed into a sorting method. 在我的代码中,我有许多ArrayList传递给排序方法。 Each of these ArrayLists have different Generic types, but all of these types are implementations of Sorter. 这些ArrayList中的每一个都有不同的Generic类型,但是所有这些类型都是Sorter的实现。 The sorting method is designed to accept ArrayLists of the type Sorter. 排序方法被设计为接受Sorter类型的ArrayLists。 My problem is that I have not found a way to cast the types of the arraylists to their super type so that they can be passed into the sorter method. 我的问题是我还没有找到一种将arraylist的类型转换为它们的超类型的方法,以便可以将它们传递到sorter方法中。 Here is what the format of the sorter method is: 这是sorter方法的格式:

public static ArrayList<Sorter> quicksort(ArrayList<Sorter> members);

The class Spatial is an implementation of sorter as follow: Spatial类是sorter的一个实现,如下所示:

public abstract class Spatial implements Sorter

However when the quicksort method is called is generates an error (children is an ArrayList of the type Spatial): 但是,当调用quicksort方法时会生成错误(子项是Spatial类型的ArrayList):

children = ListSorter.quicksort(children);

Any ideas? 有任何想法吗?

Try this: 尝试这个:

public static <T extends Sorter> ArrayList <T> quicksort(ArrayList<T> members);

Or even better, this: 甚至更好:

public static <T extends Sorter> List <T> quicksort(List<T> members);

Generics in Java are not covariant , ie List<Sorter> is not a base class of List<Spatial> . Java中的泛型不是协变的 ,即List<Sorter>不是List<Spatial>的基类。 See this article for why not: http://www.ibm.com/developerworks/java/library/j-jtp01255/index.html . 请参阅本文以了解为什么不这样做: http : //www.ibm.com/developerworks/java/library/j-jtp01255/index.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM