考虑存储在哈希图中的数据:
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;
}
输入查询内容 | 预期回报 |
---|---|
|
车辆对象1 |
|
车辆对象1 |
|
空 |
|
车辆对象2 |
|
车辆对象3 |
|
空 |
是否有一种更有效的方法来查询 Hashmap,以便如果键对象中的某个字段为 null,则将其视为 Any Match? 现在,我必须查询两次才能使其工作。有没有办法让它更快,这样哈希图就不会被查询两次?
所以答案是肯定的,解决方案是阅读 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 一定可以简化。