커스텀 객체 배열에 대해 Arrays.binarySearch를 사용해야합니다.Java Arrays.binarySearch with compareTo
class Range implements Comparable<Range>{
public int bottom;
public int top;
public Range(int botIn, int topIn) {
this.bottom = botIn;
this.top = topIn;
}
@Override
public int compareTo(Range compareRange) {
int compareQuantity = ((Range) compareRange).bottom;
return this.bottom - compareQuantity;
}}
lowerBounds이 범위 요소의 배열 내 주요 내가 첫 번째 통화 Arrays.sort(lowerBounds);
에서 다음은 객체입니다. 이것은 잘 작동하며 내가 쓴 compareTo를 사용하여 정렬합니다. 그런 다음 Arrays.binarySearch(lowerBounds, 0)
을 호출하지만 "스레드의 예외"주 "java.lang.ClassCastException : java.lang.Integer를 compareToTest.Range로 형변환 할 수 없습니다"라는 메시지가 나타납니다.
내가 뭘 잘못하고 있니? 고맙습니다.
편집 : 여기에 주요이다 :
public static void main(String[] args)
{
int[] A = {1, 5, 2, 1, 4, 0};
// write your code in Java SE 6
Range[] lowerBounds = new Range[A.length];
for(int i=0; i< A.length; i++)
{
lowerBounds[i] = new Range(i-A[i], i+A[i]);
}
Arrays.sort(lowerBounds);
for(int i=0; i< A.length; i++)
{
System.out.println(lowerBounds[i].bottom);
}
System.out.println(Arrays.binarySearch(lowerBounds, 0));
}
키 객체 (두 번째 매개 변수) 인'Arrays.binarySearch (lowerBounds, new Range (0,0)); ' –
'binarySearch'의 두 번째 매개 변수는 검색 할 값이므로 int가 아니라 'Range' 객체 여야합니다. – jCoder