我有 2 个类别:卡车和轿车。当发生某些操作时,我想将一辆轿车添加到 Truck 类的 hashMap 中。该 map 显示了卡车 cargo 中目前有哪些轿车。我不希望 Truck 和 Sedan 彼此了解,因此我在 CarManager 中创建了一个 Sedan 可以调用的方法,该方法传递轿车的 id 以及 Sedan 想要添加到的卡车的 id。然后 CarManager 将通知 Truck 有一辆轿车想要添加到列表中。问题是我不知道 CarManager 将如何通知卡车以及我应该在 addSedan 方法中拥有什么。我在 CarManager 中有一个 HashMap,其中包含 CarEntities 的集合。 Truck 的 addCar 方法无法被 CarManager 访问,因为它不在界面中,而且我不想将其添加到界面中,因为并非所有 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 接口(interface)添加两个方法:
boolean canBeLoadedWithCars();
void addCar(CarEntity c) throws IllegalStateException;
卡车可以装载汽车,因此通过返回 true 来实现第一种方法。其他的返回 false。
addCar
方法Truck
将汽车添加到其 map 中,而其他实现则抛出 IllegalStateException,因为它们无法加载汽车。
所以addCar
经理的方法变成
CarEntity truck = hashMap.get(truckId);
if (truck.canBeLoadedWithCars() {
truck.addCar(sedan);
}
关于java - 在Java中调用HashMap中对象的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7898818/