我得到了一些包含 Person 对象数组的代码,我将编写方法来执行二进制搜索并覆盖 Person 类中的 compareto 方法,以根据姓氏和名字进行比较。
public static int binarySearch( Person[] persons, Person key )
{
int low = 0;
int high = persons.length - 1;
return binarySearch(persons, key, low, high);
}
private static int binarySearch( Person[]persons, Person key, int low, int high )
{
if(low > high) //The list has been exhausted without a match.
return -low - 1;
int mid = (low + high) / 2;
if (persons[mid] == key)
return mid;
if(persons[mid] < key) //!!**'The < operator is undefined for the type'
return binarySearch(persons, key, low, mid-1);
else
return binarySearch(persons, key, 0, persons.length -1);
}
我想我已经编写了大部分二进制搜索代码。但是,我遇到的问题是在 if(persons[mid] < key) 我收到错误“< operator is undefined for the type”。
我认为它可能与我的 compareTo 方法有关,但我似乎无法修复它
这是 compareTo 供参考
public int compareTo( Object o )
{
Person p = (Person) o;
int d = getLastName().compareTo(p.getLastName());
if (d == 0)
d = getFirstName().compareTo(p.getFirstName());
return d;
}
感谢您的任何帮助!