简体   繁体   中英

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. Each of these ArrayLists have different Generic types, but all of these types are implementations of Sorter. The sorting method is designed to accept ArrayLists of the type Sorter. 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. Here is what the format of the sorter method is:

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

The class Spatial is an implementation of sorter as follow:

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):

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> . See this article for why not: http://www.ibm.com/developerworks/java/library/j-jtp01255/index.html .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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