排序泛型类型列表 - Java

时间:2015-11-27 01:59:31

标签: java sorting generics arraylist

我必须为列表实现ArrayList和排序方法。该列表包含相同类型的对象。当我尝试使用我自己的实现对列表进行排序时,我收到此错误:

ArrayList类型中的insertSort(T [])方法不适用于参数(List)

我意识到它想要一个传递给它的数组,但我怎样才能传递列表..或者只是让它工作。我已经工作了一段时间,检查过我的书,讲课等等,但无法弄清楚。

学生班级(列表将容纳的对象)

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

实际的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;
        }
    }

}

2 个答案:

答案 0 :(得分:1)

我能想到的最简单的方法是修改insertionSort方法以获取List<T>。像,

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

答案 1 :(得分:0)

如果您希望该方法仅应用于ArrayList:

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

将整个列表作为参数并直接获取它的内部数组