seraphina
seraphina

Reputation: 343

Sorting a list of generic types - Java

I have to implement an ArrayList and a sorting method for the list. The list is holding objects of the same type. When i try to sort the list using my own implementation I get this error:

The method insertionSort(T[]) in the type ArrayList is not applicable for the arguments (List)

I realize it wants an array passed to it, but how can I pass the list.. or just get it to work. I've been working on it for a while, checked my book, lecture notes, etc. and can't figure it out.

Student class(the objects the list will hold)

public class Student implements Serializable, Comparable<Student>
{
    public int compareTo(Student other) 
    {
        if (this.lastName.equals(other.lastName))
            return this.firstName.compareTo(other.firstName);
        else if (other.getlastName().compareTo(this.getlastName()) < 0)
            return 0;
        else if (other.getlastName().compareTo(this.getlastName()) > 0)
            return -1;
        else 
            return 1;
    }
}

The actual ArrayList

public class ArrayList<T> implements Iterable<T>, List<T>
{
    protected final int DEFAULT_CAPACITY = 20;
    private final int NOT_FOUND = -1;
    protected int rear;
    protected T[] list;

    @SuppressWarnings("unchecked")
    public ArrayList()
    {
        rear = 0;
        list = (T[])(new Object[DEFAULT_CAPACITY]);
    }
    public static <T extends Comparable<? super T>> void insertionSort(T[] a)
    {
        for(int index = 0; index < a.length; index++)
        {
            T key = a[index];
            int position = index;
            while(position > 0 && a[position-1].compareTo(key) > 0)
            {
                a[position] = a[position-1];
                position--;
            }
            a[position] = key;
        }
    }

}

Upvotes: 0

Views: 1343

Answers (2)

zapl
zapl

Reputation: 63955

If you want that method to apply only to your ArrayList:

public static <T extends Comparable<? super T>> void insertionSort(ArrayList<T> list)
{
    T[] a = list.list;
    ...

take the whole list as parameter and get it's internal array directly

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201439

The easiest way I can think of, would be to modify your insertionSort method to take a List<T>. Something like,

public static <T extends Comparable<? super T>> void insertionSort(List<T> a) {
    final int len = a.size(); // <-- from a.length
    for (int index = 0; index < len; index++) {
        T key = a.get(index); // <-- from a[index]
        int position = index;
        while (position > 0 && a.get(position - 1).compareTo(key) > 0) {
            a.set(position, a.get(position - 1)); // from a[position] = a[position-1];
            position--;
        }
        a.set(position, key); // <-- from a[position] = key;
    }
}

Upvotes: 1

Related Questions