【发布时间】: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