提高输入查询与数据不匹配时的哈希图查询性能

Improving hashmap query performance when input query doesnt match the data

提问人:Matrix 提问时间:11/11/2023 更新时间:11/11/2023 访问量:20

问:

考虑存储在哈希图中的以下数据:

VIN 最后 4 个 车牌
1234 车辆对象1
2222 美国广播公司123 车辆对象 2
5678 美国广播公司123 车辆对象3
5678 XYZ123型 车辆对象4
class VehicleKey{
 String vin4;
 String lPlate;
  public VehicleKey(String vin4, String lPlate){
   this.vin4=vin4;
   this.lPlate=lPlate;
  }
}
HashMap<VehicleKey,Object> vehicleMap = new HashMap<>();
vehicleMap.put(new VehicleKey("1234",null),VehicleObject1);
vehicleMap.put(new VehicleKey("2222","ABC123"),VehicleObject2);
vehicleMap.put(new VehicleKey("5678","ABC123"),VehicleObject3);
vehicleMap.put(new VehicleKey("2222","XYZ123"),VehicleObject4);
Vehicle findVehicle(String vin4, String lPlate){
 Vehicle vehicle = vehicleMap.get(vin4,lPlate);
 if (vehicle==null)
  vehicle = vehicleMap.get(vin4,null)
 return vehicle;
}

输入查询 预期回报
findVehicle("1234","Blah123") 车辆对象1
findVehicle("1234",null) 车辆对象1
findVehicle("2222","Blash123")
findVehicle("2222","ABC123") 车辆对象 2
findVehicle("5678","ABC123") 车辆对象3
findVehicle("5678",null)

有没有更有效的方法来查询 Hashmap,以便在键对象中的某个字段为 null 时将其视为 Any Match? 现在,我必须查询两次才能使其正常工作。有没有办法使这更快,这样哈希图就不会被查询两次?

Java 性能 哈希图

评论

0赞 user207421 11/11/2023
什么?中没有这样的方法。vehicleMap.get(vin4,lPlate)HashMap

答:

0赞 Michał Łukasik 11/11/2023 #1

所以答案是肯定的,解决方案是阅读 HashMap 文档或一些教程。

HashMap 是一个基于密钥哈希的映射。它支持 O(1) get/put 操作。键必须具有 hashCode() 和 equals() 的一致实现才能正常工作。因此,在代码键中,VehicleKey 必须覆盖 hashCode/equals 方法。

hashCode 方法示例

@Override
public int hashCode() {
    int result = vin4 != null ? vin4.hashCode() : 0;
    result = 31 * result + (lPlate != null ? lPlate.hashCode() : 0);
    return result;
}

更重要的是。Equals 方法:

@Override
public boolean equals(Object o) {
    if (this == o) return true;//check if points to same object instance
    if (o == null || getClass() != o.getClass()) return false;//if one of object is null or different class

    VehicleKey that = (VehicleKey) o;
    if (Objects.equals(vin4, that.vin4) && Objects.equals(lPlate, that.lPlate)) {
        return true;
    }
    if (Objects.equals(vin4, that.vin4) && lPlate == null || that.lPlate == null) {
        return true;
    }
    return Objects.equals(lPlate, that.lPlate) && vin4 == null || that.vin4 == null;
}

可以肯定的是,if's must 可以简化。