我必須爲列表實現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;
}
}
}