我的程序实现了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)
。在我开始编写代码之前,你能告诉我我是否错过或忘记了任何东西吗?
** * ** * ** * ****UPDATE* ** * ** * ** * * * * ** * ** * ** * ** * ** * ** *
我刚刚创建了一个名为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收到以下错误,当我编译。
类型集合中的方法sort(List,Comparator)不适用于参数(LinkedList,ProductComparator)。
有没有人知道我为什么得到这个错误,并可以指出我在正确的方向来解决它?
更新了您的问题:您是否已在ProductComparator中正确实施了Comparator? –