我有一个父接口和一个子接口,对象将实现。我创建了一个子接口,因为我想要一个特定的VehicleEntity对象说Truck
将自己添加到Car
中的HashMap。 Truck
将调用VehicleManager的addToCar()
方法,该方法将Truck对象添加到Car的hashMap中。我遇到的问题是CarEntity ce = ve;
。 Netbeans告诉我将ve
投射到CarEntity但我不想这样做。代码行不应该有效(假设for循环正在查看的对象是Car对象)?我该如何解决这个问题?
public interface VehicleEntity {
getId();
getSpeed();
move();
}
public interface CarEntity extends VehicleEntity{
addToCar(String c);
}
public class Car implements CarEntity{
HashMap<String, VehicleEntity> cars = new HashMap<String, VehicleEntity>();
public void addToCar(String c) {
cars.add(c);
}
}
public class VehicleManager {
HashMap<String, VehicleEntity> vehicles = new HashMap<String, VehicleEntity>();
public void reportToCar(String id) {
for (VehicleEntity ve : ve.values()) {
if (ve.getId().equals(id)) {
CarEntity ce = ve; // Issue here
}
}
}
答案 0 :(得分:5)
真的,这根本不是有效的。您可以在不进行转换的情况下从特定转移到常规,但不能再转回。例如,您可以将ArrayList存储在List变量中,但是您无法获取List并将其放入ArrayList变量中而不进行强制转换。以同样的方式,你不能拿车并说它是没有明确铸造的汽车。
因此,在这种情况下,因为您知道车辆是汽车,所以明确地投入汽车。
答案 1 :(得分:0)
我不完全确定你要到达的是什么,所以我要先用最好的猜测列出一些纠正的课程......
public interface VehicleEntity {
public String getId();
public String getSpeed();
public void move();
}
public interface CarEntity extends VehicleEntity {
public void addToCar(String key, CarEntity c);
}
import java.util.HashMap;
public class Car implements CarEntity{
HashMap<String, VehicleEntity> cars = new HashMap<String, VehicleEntity>();
@Override
public void addToCar(String key, CarEntity car) {
cars.put(key, this);
}
@Override
public String getId() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getSpeed() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void move() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
...然后使用泛型显示一个很酷的技巧:
import java.util.HashMap;
public class VehicleManager {
HashMap<String, VehicleEntity> vehicles =
new HashMap<String, VehicleEntity>();
public <T extends VehicleEntity> T report(String id) {
for(VehicleEntity ve : vehicles.values()) {
if(ve.getId().equals(id)) {
@SuppressWarnings("unchecked")
T ce = (T)ve;
return ce;
}
}
return null;
}
public void test() {
final Car c = report("test");
}
}
我已使用report
扩展T
参数化了方法VehicleEntity
。它将返回该类型的T
。在方法test()
中使用此功能时,我们已声明我们需要Car
。现在,一些类型推断将继续进行,为类型report
自动调用方法Car
。如果具有给定id的地图中的VehicleEntity
不是Car
,我们将获得ClassCastException,因为我们在该上下文中调用thet方法时尝试强制转换为Car