【发布时间】:2012-11-12 15:51:02
【问题描述】:
我的程序实现了一个 Product 类,其对象包含以下实例变量:name、priority、price 和 amount。
我有一个LinkedList 的Product 对象,在对LinkedList 执行任何其他操作之前,我需要对其进行排序。
我想首先按优先级(从最低到最高)对列表进行排序。如果优先级相同,则查看价格(从低到高),然后查看名称(按字母顺序)。
我已经阅读了大量关于Collections.sort、Comparable 和Comparator 的内容。我相信我需要使用Comparable 接口并实现compareTo 方法。我的想法是,因为priority、price 和name 都具有“自然”顺序,所以使用Comparable 更有意义。
public class Product extends ProductBase implements PrintInterface, Comparable<Product>{
private String name;
private int priority;
private int cents;
private int quantity;
// setters and getters
/**
* Compare current Product object with compareToThis
* return 0 if priority, price and name are the same for both
* return -1 if current Product is less than compareToThis
* return 1 if current Product is greater than compareToThis
*/
@override
public int compareTo(Product compareToThis)
}
然后,当我想对我的 LinkedList 进行排序时,我只需调用 Collections.sort(LinkedList)。在我开始编写代码之前,你能告诉我我是否遗漏或忘记了什么吗?
************ *更新********** *************** ******
我刚刚使用比较方法创建了一个名为 ProductComparator 的单独类。
这是 LinkedList 类的一部分。
import java.util.Collections;
public class LinkedList {
private ListNode head;
public LinkedList() {
head = null;
}
// this method will sort the LinkedList using a ProductComparator
public void sortList() {
ListNode position = head;
if (position != null) {
Collections.sort(this, new ProductComparator());
}
}
// ListNode inner class
private class ListNode {
private Product item;
private ListNode link;
// constructor
public ListNode(Product newItem, ListNode newLink) {
item= newItem;
link = newLink;
}
}
}
我在编译时从 IDE 收到以下错误。
Collections 类型中的方法 sort(List, Comparator) 不适用于参数 (LinkedList, ProductComparator)。
有谁知道我为什么会收到此错误并可以指出正确的方向来解决它?
【问题讨论】:
-
对于您更新的问题:您是否在 ProductComparator 中正确实施了 Comparator?
标签: java comparator comparable