Question

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?

Was it helpful?

Solution

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

OTHER TIPS

Generics in Java are not covariant, i.e. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top