1

I have a problem with HashMap. This problem is same for any other generics (LinkedList etc). Let's say that I have 2 classess:

Class A:

public class A {
    public void aMethod() {
        System.out.println("A");
    }

Class B, extends A:

public class B extends A {
    public void bMethod() {
        System.out.println("B");
    }

Now in the class with main method I'm making a hashmap to store instances of this 2 classess:

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();

    }
}

Is there any way to store object from different classess in one HashMap, which doesn't require casting to use other (extended) methods ?

I'd like to use:

myObjects.get("objB")).bMethod();

Without casting. Thank you.

RichardK
  • 3,228
  • 5
  • 32
  • 52
  • 1
    Without casting, and calling arbitrary methods? Of course not. That's the point of Java, to explicitly avoid not knowing what you're working with. – Dave Newton Oct 03 '14 at 13:36
  • 1
    If you need to cast often, maybe it means you can improve the design of your `A` and `B` classes. – ericbn Oct 03 '14 at 13:39

1 Answers1

3

No, there isn't. By parameterizing the type with A you've told the compiler that the only thing it can count on is that the object in the map is an instance of A. If you put a subclass in there, it will accept it but it can't know that that particular item is B so you will always have to cast.

Chris
  • 22,923
  • 4
  • 56
  • 50