我正在尝试对一个充满客户对象的ArrayList进行排序。
ArrayList Cust = new ArrayList();
Cust.add(new Customer("John",15,"New York",200));
Cust.add(new Customer("Moya",25,"Randfontein",200));
Cust.add(new Customer("Sue",44,"Jersey",100));
Cust.add(new Customer("Mpho",23,"London",250));
我有一个外来类排序,它包含一个实现Comparable接口的插入排序方法。
public static <AnyType extends Comparable<? super AnyType>> void insertionSort(ArrayList<AnyType> a) {
for (int p = 1; p < a.size(); p++) {
AnyType tmp = a.get(p);
int j;
for (j = p; j > 0 && tmp.compareTo(a.get(j - 1)) < 0; j--) {
a.set(j, a.get(j - 1));
}
a.set(j, tmp);
}
我尝试在主类中使用此方法根据Customer的年龄(第二个元素)对ArrayList进行排序。
Sorting.insertionSort(CustList);
这给了我一个错误:找不到适合insertSort的方法(java.util.ArrayList)Sorting.insertionSort(CustList);
帮助我__(ツ)_ /¯
根据要求,以下是完整代码:
public interface Comparator<AnyType> {
/**
* Return the result of comparing lhs and rhs.
* @param lhs first object.
* @param rhs second object.
* @return < 0 if lhs is less than rhs,
* 0 if lhs is equal to rhs,
* > 0 if lhs is greater than rhs.
*/
int compare( AnyType lhs, AnyType rhs );
}
///
public final class Customer implements Comparable<Customer> {
String name;
int age;
String city;
int loyaltyPoints;
public Customer(String n, int a, String c, int lP) {
name=n; age=a; city=c; loyaltyPoints=lP;
}
public String toString() {
return "Customer " + name + " from " + city + " is " + age + " years old, and has loyaltypoints of " + loyaltyPoints;
}
public int compareTo(Customer rhs) {
return this.age - rhs.age;
}
}
///
public final class Sorting {
public static <AnyType> void insertionSort(ArrayList<AnyType> a, Comparator<? super AnyType> cmp) {
}
public static <AnyType extends Comparable<? super AnyType>> void insertionSort(ArrayList<AnyType> a) {
for (int p = 1; p < a.size(); p++) {
AnyType tmp = a.get(p);
int j;
for (j = p; j > 0 && tmp.compareTo(a.get(j - 1)) < 0; j--) {
a.set(j, a.get(j - 1));
}
a.set(j, tmp);
}
}
}
///
public class Test{
public static void main(String[] args) {
// Add some customers to an arraylist
ArrayList Cust = new ArrayList();
Cust.add(new Customer("John",45,"Tokyo",200));
Cust.add(new Customer("Johna",25,"London",200));
Cust.add(new Customer("James",33,"New York",100));
Cust.add(new Customer("Jack",23,"Utah",250));
Cust.add(new Customer("Janet",25,"Jersey",250));
Cust.add(new Customer("Jared",28,"Gotham",250));
Sorting.insertionSort(Cust);
}
}
答案 0 :(得分:2)
使用ArrayList<Customer> custList = new ArrayList<>();
并确保&#39;客户&#39;实现&#39; Comparable&#39;。
ArrayList Cust
的问题是Java不能假设列表元素的类型,除了它们是Object
,而不是Comparable
。
更新:
Cust.add(...)
应该发出警告&#39;未经检查的调用“添加(E)&#39;作为原始类型ArrayList&#39; ArrayList Cust = new ArrayList<>();
行替换为ArrayList<Customer> Cust = new ArrayList<>();
其他一些说明:
public static <AnyType extends Comparable<? super AnyType>> void insertionSort(ArrayList<AnyType> a)
使用public static <AnyType extends Comparable<AnyType>> void insertionSort(List<AnyType> a)
- 注意它预计&#39;列表&#39;而不是&#39; ArrayList&#39;