2014-11-24 1 views
-2

... 는 가능한 한 빨리 도와주세요 ..Collections.binarySearch 반환 negetive 정수

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Comparator; 

class Car{ 

    public int speed; 

    public Car(int speed){ 
     this.speed = speed; 
    } 
} 

class Compare implements Comparator<Car>{ 

    public int compare(Car C1, Car C2) { 

     if(C1.speed < C2.speed) 
      return -1; 
     else 
      return 1; 

    } 

} 

public class Main{ 
    public static void main(String[] args){ 

     Car c ; 

     ArrayList<Car> a = new ArrayList<Car>(); 

     for(int i = 0 ; i < 5 ; i++){ 
       a.add(new Car(i)); 
     } 

     Collections.sort(a, new Compare()); 

     System.out.println(Collections.binarySearch(a, new Car(0), new Compare())); 

    } 
} 

을 좀 음수로 출력을 얻고있다.

+0

비교 메서드에 0을 반환하는 조건이 없으므로 –

+0

예, 그게 실수였습니다. 고맙습니다. –

답변

1

비교기가 잘못되었습니다. 두 자동차의 속도가 같으면 0을 반환합니다.

A가 B, A > B 당신이 compare(A, B)를 사용하는 경우와 같은 속도가있는 경우, 코딩으로

, 당신은 비교기 계약의 명백한 위반이다, compare(B, A)를 사용하는 경우 B > A.

비교기에 의해 자동차가 다른 자동차와 같은 것으로 간주되지 않으므로 binarySearch는 검색된 자동차와 동일한 자동차를 찾지 않으므로 문서화 된대로 음수 값을 반환합니다.

관련 문제