繁体   English   中英

在Java中的HashMap中调用对象的方法

[英]Calling a method of an Object in a HashMap in Java

我有2节课:卡车和轿车。 发生某些操作时,我想将轿车添加到Truck类的hashMap中。 该地图显示了卡车中目前有哪些轿车。 我不希望Truck和Sedan彼此了解,所以我在CarManager中创建了Sedan可以调用的方法,该方法传递了轿车ID和想要添加到的Truck ID。 然后,CarManager将通知Truck轿车要添加到列表中。 问题是我不知道CarManager将如何通知卡车以及该addSedan方法中应包含的内容。 我在CarManager中确实有一个HashMap,它具有CarEntities的集合。 CarManager无法访问Truck的addCar方法,因为它不在界面中,并且我不想在界面中添加它,因为并非所有CarEntity都会使用它。 有人可以帮忙吗?

public interface CarEntity {
    String getId();
    double getSpeed();
    void move();
}

public class CarManager {
    private HashMap<String, CarEntity> hash = new HashMap<String, CarEntity>();
    public void addSedan(String carId, String truckId) {
    ???
    hash.get(truckId).addCarr(carId); //I don't think this will work
    }

}

public class Truck implements CarEntity { 
    private HashMap<String, CarEntity> cargo = new HashMap<String, CarEntity>();
    public void addCar(String id, CarEntity ce) {
        cargo.put(id,ce);
}

public class Sedan implements CarEntity {
    CarManager.addSedan("Car 1", "Truck 5");
}

如果您可能不使用强制类型转换和instanceof,而必须使用多态性,则在CarEntity接口中添加两个方法:

boolean canBeLoadedWithCars();
void addCar(CarEntity c) throws IllegalStateException;

卡车可以装满汽车,并通过返回true来实现第一个方法。 其他的返回false。

TruckaddCar方法将Truck添加到地图中,而其他实现则抛出IllegalStateException,因为它们无法加载汽车。

因此,管理器的addCar方法变为

CarEntity truck = hashMap.get(truckId);
if (truck.canBeLoadedWithCars() {
    truck.addCar(sedan);
}

我想你可以做的一件事是

CarEntity t = hash.get(truckId); 
if (t instanceof Truck)
   downcast car entity to truck
   call add car method

答案取决于谁在采取行动。 如果Sedan将自己添加到卡车中,则您应该具有addTruck方法,该方法会将所有卡车添加到管理器中。 经理将Truck存储在Map

private Map<String, Truck> trucks = new HashMap<String, Truck>();
public void registerTruck(Truck truck) {
    trucks.put(truck.getId(), truck);
}

然后,管理器上的addCar()方法将执行以下操作:

public void addCar(String truckId, CarEntity car) {
    Truck truck = trucks.get(truckId);
    // null handling needed here
    truck.addCar(car);
}

相反,如果卡车载有汽车,则您可以注册汽车。 如果您需要同时输入字符串ID,则需要同时注册汽车和卡车,并执行类似的操作:

private Map<String, Truck> trucks = new HashMap<String, Truck>();
private Map<String, Sedan> sedans = new HashMap<String, Sedan>();

public void registerTruck(Truck truck) {
    trucks.put(truck.getId(), truck);
}
public void registerSedan(Sedan sedan) {
    sedans.put(sedan.getId(), sedan);
}

public void addSedan(String sedanId, String truckId) {
    Sedan sedan = sedans.get(sedanId);
    Truck truck = trucks.get(truckId);
    // null handling needed here
    truck.addCar(sedan);
}

通常,我们使用Java接口来完成去耦。 Truck类应该能够在其负载中添加CarEntity而不知道它是Sedan 在这种情况下, Truck上的addCar(CarEntity car)方法听起来不错。 Sedan永远不会知道它在Truck并且所有卡车都知道这是通过CarEntity接口公开的方法。 在这种情况下,经理可能会离开。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM