【问题标题】:Sorting a list of generic types - Java对泛型类型列表进行排序 - Java
【发布时间】:2016-03-01 04:18:14
【问题描述】:

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

ArrayList类型中的insertionSort(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;
    }
}

实际的数组列表

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

}

【问题讨论】:

    标签: java sorting generics arraylist


    【解决方案1】:

    我能想到的最简单的方法是将您的insertionSort 方法修改为采用List&lt;T&gt;。类似的,

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2019-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多