我需要在自定义对象数组上使用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;
}}
以我主我第一呼叫Arrays.sort(lowerBounds);
其中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));
}
在哪里'的main()'-code?但我的猜测是尝试'Arrays.binarySearch(lowerBounds,new Range(0,0));'作为关键对象(第二个参数)与您传递的数组的类型相同。 –
'binarySearch'的第二个参数是要搜索的值,因此它不应该是一个int值,而应该是'Range'对象。 – jCoder