[英]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。
Truck
的addCar
方法將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.