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

问题描述 投票:0回答:1

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

VIN 最后 4 个 车牌 详情
1234 车辆对象1
2222 ABC123 车辆对象2
5678 ABC123 车辆对象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 performance hashmap
1个回答
0
投票

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

HashMap 是基于键散列的映射。它支持 O(1) 获取/放置操作。 键必须具有一致的 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;
}

还有更重要的一点。等于方法:

@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 一定可以简化。

© www.soinside.com 2019 - 2024. All rights reserved.