【发布时间】:2021-12-20 22:33:47
【问题描述】:
我被要求按型号类型对汽车数组进行排序,然后使用 Arrays.binarySearch 搜索具有该型号字段的汽车。问题是当进行搜索时,它什么也找不到(即使模型在那里)。
下面是我的代码和输出:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class CarApplication
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
Car car1 = new Car("Toyota", "Corolla" , 1996);
Car car2 = new Car("Nissan", "Murano" , 2004);
Car car3 = new Car("Mazda" , "Miata", 1999);
Car car4 = new Car("Ford", "Mustang" , 2013);
Car car5 = new Car("Chevy", "Volt" , 2020);
Car car6 = new Car("Tesla", "Model X" , 2016);
Car [] myCars = {car1, car2, car3, car4, car5, car6};
Arrays.sort(myCars, new CompareByModel());
System.out.println("Sorting by Model only (Comparator)");
for (Car car:myCars)
System.out.println(car);
System.out.println("Enter the name of the car model you wish to purchase: ");
String model = keyboard.nextLine();
//binary search
Car key = new Car("", model, 0); // set the name field so we can look for a match in array
int location = Arrays.binarySearch(myCars, 0, myCars.length, key, new CompareByModel());
//print message
if (location < 0)
System.out.println("Sorry, please check back next week.");
else
{
System.out.println("We have a " + model + " in location" + myCars[location]);
}
}
}
//Comparator
class CompareByModel implements Comparator<Car>
{
public int compare(Car c1, Car c2) {
int makeResult = c1.getCarMake().compareTo(c2.getCarMake());
int modelResult = c1.getCarModel().compareTo(c2.getCarModel());
return (modelResult == 0) ? makeResult: modelResult;
}
}
输出: 输入您要购买的车型名称:
伏特
抱歉,请下周再来看看。
【问题讨论】:
-
为了将
CompareByModel用作Comparator到binarySearch,您还需要在key中包含汽车的make。否则,您需要创建一个Comparator,它将忽略make并仅查看model。在您的示例中,我得到了-6的结果,考虑到应用的偏移量,使其变为-5,当转换为正数时,变为5,这实际上是所需的元素