這裏是我的接口類的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