2015-01-28 2 views
3

에 나는 내가 트리 맵에 넣어 객체를 정의하는 다음 두 개의 클래스를하고자했다 나는 다음 트리 맵하고 싶습니다 :오류 <개체, 개체> TreeMap의

import java.util.TreeMap; 

// In main ... 
TreeMap<GeneKey, GeneValue> samples = new TreeMap<GeneKey, GeneValue>(); 

String a = "test"; 
int b = 100; 

String c = "test again"; 
String d = "test yet again"; 

// Try to put these objects into the tree map. 
samples.put(new GeneKey(a, b) ,new GeneValue(c,d)) 

을하지만, 나는 다음과 같은 오류가 발생합니다 :

Exception in thread "main" java.lang.ClassCastException: GeneKey cannot be cast to java.lang.Comparable 

왜 TreeMap 키를 사용하여 설정할 수 없는지 알고 싶습니다. 내 TreeMap을 초기화 할 때 해당 개체를 지정 했더라도 GeneKey : GeneValue 값. 이 두 개체를 .put()하기 위해지도를 초기화하는 방법.

+3

'GeneKey'에'Comparable'을 구현 하시겠습니까? – Reimeus

+0

이것은 거의 정확하게 http://stackoverflow.com/questions/28178337/returning-a-sortedset/28178380#28178380의 속임수입니다. –

답변

7

TreeMap이 순서 컨테이너입니다 감사합니다 당신은 키 또는 항목을 요청할 때, 당신이 특정 순서로 얻을.

주문은 제공하는 키에 따라 다릅니다. 모든 hashCodeequals 공급 Object, 상속 때문에,

class GeneKey implements Comparable<GeneKey> { 

    String PN; 
    int PW; 

    // Generator makes unique TreeMap key. 
    GeneKey(String a, int b){ 
     this.PN = a; 
     this.PW = b; 
    } 
    public int compareTo(GenKey other) { 
     int res = PN.compareTo(other.PN); 
     return (res != 0) ? res : Integer.compare(PW, other.PW); 
    } 
} 

이 해시 기반 컨테이너에 대한 요구 사항되지 않습니다 : 키를 명령 할 용기 위해서는, 각각의 키는 Comparable 인터페이스를 구현해야합니다.

+0

완벽. 고맙습니다. – Malonge

관련 문제