2013-11-22 2 views
8

줄 은 "기본 형식 double에서 compareTo (double)을 호출 할 수 없습니다"라는 오류 메시지를 표시합니다.. 이 문제를 해결하는 방법?기본 형식 double에서 compareTo (double)을 호출 할 수 없습니다.

/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ 
/*:: This function implements a comparator of double values  :*/ 
/*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ 
private class ArrayIndexComparator implements Comparator<Integer> 
{ 
    private final double[] array; 

    public ArrayIndexComparator(double[] array) 
    { 
     this.array = array; 
    } 

    public Integer[] createIndexArray() 
    { 
     Integer[] indexes = new Integer[array.length]; 
     for (int i = 0; i < array.length; i++) 
     { 
      indexes[i] = i; // Autoboxing 
     } 
     return indexes; 
    } 

    @Override 
    public int compare(Integer index1, Integer index2) 
    { 
     // Autounbox from Integer to int to use as array indexes 
     return array[index1].compareTo(array[index2]); 
    } 
} 


double[] dist = new double[centroids.size()]; 
// fill array...  
ArrayIndexComparator comparator = new ArrayIndexComparator(dist); 
Integer[] indexes = comparator.createIndexArray(); 
Arrays.sort(indexes, comparator); 
+2

더블 클래스 사용) – Alessio

+0

더 많은 자바 문서를 살펴보면 java.lang.Double 패키지로 이동합니다.이 클래스를 래퍼 클래스라고하고 모든 원시 유형의 Java에서는 해당 래퍼 클래스가 있습니다. java.lang 패키지 –

+0

다음은 문서 링크입니다 http://docs.oracle.com/javase/7/docs/api/ –

답변

15

double[] array;의와 시도 이 같은 static compare method의 전화와는 :

return Double.compare(array[index1], array[index2]); 

이것은 당신이 프리미티브의 배열에 double의 유지 및 인스턴스 메서드를 호출하기 전에 오토 박싱 방지 할 수 있습니다. 기본 유형은 compareTo를 사용하지 않는 대한

+0

+1 Double.compare (...);)을 완전히 잊어 버렸습니다 – Thomas

+0

이 경우 역순으로 정렬 하시겠습니까? 어디에 넣을 까, Collections.reverseOrder()? –

+0

@KlausosKlausos'Collections.reverseOrder()'는 자연 순서를 바꾸기위한 것입니다. 비교자를 사용하기 때문에'Double '을 호출하여 비교자를 바꿀 수 있습니다.생성자에 여분의'boolean isReverseOrder' 플래그를 추가하여 멤버 변수에 저장하고'isReverseOrder'가 실행될 때 compare 메소드 내에서 비교 결과를 반전시킴으로써 compare (array [index2], array [index1])' 설정됩니다. – dasblinkenlight

1

Java 원시 타입에는 메소드가 없습니다. 대신 기본 데이터 형식을 사용하면 래퍼 클래스를 사용할 수 있습니다.

변화

return array[index1].compareTo(array[index2]); 

return new Double(array[index1]).compareTo(array[index2]); 

또는

하려면 인스턴스 메소드의 전화를 교체 Double[] array; 대신

1

, == 대신

를 사용하지만 compareTo을 사용하려면 단지로,

Double[] dist = new Double[centroids.size()]; 
+1

'=='는'compareTo'와 같지 않지만'equals'와 같습니다. – Thomas

0

기본 유형이 비교기에 의해 직접적으로 비교 될 수없는 두 배열을 만들 인터페이스는 collator와 RuleBasedCollator에 의해서만 구현됩니다. 래퍼 클래스는 Comparator를 구현하지 않습니다. 이로 인해 컴파일러는 자동 상자를 만들 수 없습니다.

Double 클래스를 보면 compare 메소드를 제공하는 inbuilt 메소드가 있습니다.

public static int compare(double d1, double d2)

결과 : 0 값 D1이 d2와 동일한 경우; d1가 수치 적으로 d2보다 작은 경우는 0보다 작은 값. d1이 d2보다 큰 경우 0보다 큰 값입니다.

역순 : 전체 표현식에 -1을 곱합니다.

관련 문제