这里是我的接口类的Java Collections.sort(),即使媲美声明
public interface Thing {
int getVolume();
}
这里没有工作是实现东西
Item.java
public class Item implements Thing, Comparable<Thing> {
private String name;
private int volume;
public Item(String name,int volume){
this.name = name;
this.volume = volume;
}
@Override
public int getVolume() {
return this.volume;
}
public String getName(){
return this.name;
}
@Override
public String toString(){
return name+" ("+volume+" dm^3)";
}
// @Override
@Override
public int compareTo(Thing another) {
if(this.getVolume() < another.getVolume()){
return -1;
}
if(this.getVolume() == another.getVolume()){
return 0;
}
else{
return 1;
}
}
}
类当我尝试使用以下命令运行主程序时,它运行正常 // main program.java
public class Main {
public static void main(String[] args) {
// test your program here
List<Item> items = new ArrayList<Item>();
items.add(new Item("passport", 2));
items.add(new Item("toothbrash", 1));
items.add(new Item("circular saw", 100));
Collections.sort(items);
System.out.println(items);
}
}
但是,当我尝试在它实现Thing接口,另一个类运行Collections.sort(),我得到一个错误
这里框类,它实现的事情接口,当我尝试运行Collections.sort(store)在void sort()函数中给出了一个错误,即使商店是List并且Box类实现了Thing接口,并且我已经在Item.java类中为Thing定义了类似的东西
Box.java
public class Box implements Thing {
private int maximumCapacity;
private List<Thing> store;
public Box(int maximumCapacity) {
this.maximumCapacity = maximumCapacity;
this.store = new ArrayList<Thing>();
}
public boolean addThing(Thing thing) {
// I.E. if the item added does not make the total volume go to max capacity only
// then add
if (this.getVolume() + thing.getVolume() < this.maximumCapacity) {
store.add(thing);
return true;
}
return false;
}
@Override
public int getVolume() {
// we calculate things of all items in the boxes (current value)
int currentWeight = 0;
for (Thing t : store) {
currentWeight += t.getVolume();
}
return currentWeight;
}
public List<Thing> getStore() {
return store;
}
public int numOfItems(){
return this.store.size();
}
public void sort(){
Collections.sort(store); // *****does not work ****//
}
}
它给出了上面的错误排序为“没有合适的方法找到 排序(列表<东西>)”。
我的问题是,如果它可以在main.java程序中的项目被列为List,那么为什么它不能在这里工作? 如何解决它?
的建议你'Box'类未实现'Comparable'。你如何期待'sort'知道如何排序? – njzk2