2012-10-24 4 views
3

튜토리얼을 읽었지만 Country 클래스 Comparable을 내 BST으로 만들지 못했습니다.자신의 클래스를 'Comparable'로 만들기

홈페이지 :

BinarySearchTree A = new BinarySearchTree(); 
Country a = new Country("Romania", "Bucharest", 1112); 
A.insert(a); 

나라 클래스 :

public int compareTo(Object anotherCountry) throws ClassCastException { 
    if (!(anotherCountry instanceof Country)) 
     throw new ClassCastException("A Country object expected."); 
    String anotherCountryName = ((Country) anotherCountry).getName(); 
    int i = this.name.compareTo(anotherCountryName); 
    if(i < 0){ 
     return -1; 
    } else { 
     return 0; 
    } 
} 

오류 :

@Override 
public int compareTo(Object anotherCountry) throws ClassCastException { 
    if (!(anotherCountry instanceof Country)) 
     throw new ClassCastException("A Country object expected."); 
    String anotherCountryName = ((Country) anotherCountry).getName(); 
    return this.name.compareTo(anotherCountryName); 

Description Resource Path Location Type 

이름 충돌 : 타입 나라의 방법은 compareTo (개체)은 compareTo와 같은 삭제가 있습니다 (T) Comparable 유형이지만 재정의하지 않습니다. Country.java/Lab2_prob 4/src 행 17 Java 문제

Description Resource Path Location Type 
The method compareTo(Object) of type Country must override or implement a supertype method Country.java /Lab2_prob 4/src line 17 Java Problem 

및 클래스 :

public class Country implements Comparable<Country>{ 
    private String name; 
    private String capital; 
    private int area; 

Description Resource Path Location Type 

상속 된 추상 메소드 Comparable.compareTo (국가) Country.java/Lab2_prob 4/src에 라인이 자바 문제

+2

'Country' 클래스가'Comparable '을 확장합니까? –

+2

실제로 어떤 문제 또는 오류가 발생합니까? – DNA

+0

죄송합니다. 오류가 추가되었습니다. –

답변

16

귀하의 Country 클래스 :

public class Country implements Comparable<Country> 

이 그런 다음 compareTo 방법은 다음과 같아야합니다

@Override 
public int compareTo(Country anotherCountry) { 
    return anotherCountry.getName().compareTo(this.name); 
} 

compareTo의 서명. 매개 변수는 Country이 아닌 Object 유형이어야합니다. 이는 generic 형식 매개 변수가 Comparable에 있기 때문에 이루어집니다. 단점은 더 이상 유형을 확인할 필요가 없다는 것입니다. 단점은 Country 개를 다른 Country 개 개체 (또는 하위 유형)와 비교할 수 있지만 대부분의 경우 이것이 원하는 것입니다. 그렇지 않으면 type 매개 변수를 변경해야합니다. 예 : Comparable<Object>을 사용하면 compareTo의 서명은 다시 Object 일 수 있습니다. 원하는 경우 제네릭 here을 읽을 수 있습니다.

+1

'Comparable'은 단지 인터페이스라고 기억합니다. 죄송합니다. –

+0

나에게 제안한 내용을 수정 한 후 에로스를 확인해 주시겠습니까? 꽤 내 대답을 편집 –

+0

제발 –

4

Comparable을 구현해야하는 타입 나라 반환해야합니다 :

a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

그러나 코드는 -1 또는 0 만 반환합니다. 들리지 않는다. 이것은 this이 다른 객체보다 작거나 같을 수 있지만 더 클 수는 없다는 것을 의미합니다.

name.compareTo()에 의해 반환 된 값을 수정할 필요가 없습니다. 직접 반환 할 수 있습니다. Comparable를 구현해야

관련 문제