2012-12-18 149 views
-2

投例外,我有這樣的方法:爪哇 - 可比

private SortedMap<String, SpaceObjectImpl> catalog = new TreeMap<String, SpaceObjectImpl>(); 

public Collection<SpaceObject> getSpaceObjects(){ 
    SortedSet<SpaceObject> temp = new TreeSet<SpaceObject>(catalog.values()); 
    return temp; 
} 

的compareTo同時這裏定義:

public int compareTo(SpaceObjectImpl s){ 
    .... 
} 

class SpaceObjectImpl implements SpaceObject 

當我運行程序,ClassCastException被拋出。任何想法爲什麼?

錯誤:

SpaceObjectImpl cannot be cast to java.lang.Comparable(in TreeMap) 
+8

你需要有SpaceObjectImpl實現媲美。 – assylias

+0

啊多數民衆贊成它,謝謝.. :) –

回答

-1

SpaceObjectImpl必須實現Comparable接口。

以下是an example by mkyong示出這一概念:

public class Fruit implements Comparable<Fruit>{ 

    private String fruitName; 
    private String fruitDesc; 
    private int quantity; 

    public Fruit(String fruitName, String fruitDesc, int quantity) { 
     super(); 
     this.fruitName = fruitName; 
     this.fruitDesc = fruitDesc; 
     this.quantity = quantity; 
    } 

    public String getFruitName() { 
     return fruitName; 
    } 
    public void setFruitName(String fruitName) { 
     this.fruitName = fruitName; 
    } 
    public String getFruitDesc() { 
     return fruitDesc; 
    } 
    public void setFruitDesc(String fruitDesc) { 
     this.fruitDesc = fruitDesc; 
    } 
    public int getQuantity() { 
     return quantity; 
    } 
    public void setQuantity(int quantity) { 
     this.quantity = quantity; 
    } 

    public int compareTo(Fruit compareFruit) { 

     int compareQuantity = ((Fruit) compareFruit).getQuantity(); 

     //ascending order 
     return this.quantity - compareQuantity; 

     //descending order 
     //return compareQuantity - this.quantity; 

    } 
} 

這裏,Fruit類實現Comparable接口類型爲Fruit,並具有也overridencompareTo方法。

+0

啊是的,這實現失蹤,謝謝:) –

+6

-1你留着複製的東西,而適當的歸屬。 http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/ – assylias

+0

只需在最後添加一個鏈接是不是在這種情況下,歸屬不夠好。我編輯了你的答案,使其更清楚地說明代碼示例的來源。 –

0

compareTo方法是媲美,因而自定義類應該重寫使用它TreeMap.Please實現自定義類

0

您已寫入了自己compareTo()方法可比的接口定義。你需要編寫自己的compareTo()但是,需要將超過纏身,即你的類應該實現Comparable

Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort).

1

SpaceObjectImpl必須實現Comparable<SpaceObjectImpl>