2015-11-27 62 views
0

我必須爲列表實現ArrayList和排序方法。該列表保存相同類型的對象。當我嘗試使用我自己的實現對列表進行排序我得到這個錯誤:對通用類型列表排序 - Java

的方法插入排序(T [])在ArrayList類型是不適用的參數(列表)

我知道它希望的數組傳遞給它,但我怎麼能通過列表..或只是讓它工作。我一直在研究它,檢查了我的書,課堂筆記等,但無法弄清楚。

學生類(對象名單將持有)

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

} 

回答

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

如果你想這種方法只適用於您的ArrayList:

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

把整個列表作爲參數,並得到它的直接

內部數組