<分区>
我对 HashMap 有疑问。这个问题对于任何其他泛型(LinkedList 等)都是一样的。假设我有 2 个类:
A 类:
public class A {
public void aMethod() {
System.out.println("A");
}
B 类,扩展 A:
public class B extends A {
public void bMethod() {
System.out.println("B");
}
现在在带有 main 方法的类中,我正在制作一个 HashMap 来存储这 2 个类的实例:
import java.util.HashMap;
public class TestList {
public static void main(String[] args) {
//I'm making 2 objects representing A and B class:
A objA = new A();
B objB = new B();
// I'm making a HasMap storing A class objects, where I can
// also store B objects, because B is subclass of A
HashMap<String, A> myObjects = new HashMap<String, A>();
myObjects.put("objA", objA);
myObjects.put("objB", objB);
// using a method from class A is working fine on objA:
myObjects.get("objA").aMethod();
// but if I want to use a method from B class on objB
// I need to cast:
((B) myObjects.get("objB")).bMethod();
}
}
有没有什么方法可以在一个 HashMap 中存储来自不同类的对象,而不需要强制转换才能使用其他(扩展)方法?
我想使用:
myObjects.get("objB")).bMethod();
没有类型转换。谢谢。