0

How do I make a HashMap, that maps Integer or int to a class instance of a class that extends a specified Class:

public HashMap<Integer, ? extends myClass> myMap = new HashMap<Integer, ? extends myClass>();

This gives a error: Cannot instantiate the type HashMap<Integer,? extends mySuperclass> (by Eclipse)

I am not too experienced with Java and I really appreciate your answers. To make this a little bit more obvious, this is a short image explaining what I want to achieve: Click this link to see the image.

Trying to add a class that does not extend that Superclass should not work.

I'm really sorry if this has been asked already but I tried searching for a couple of terms and could not find a similar question. There was one quite similar, but I did not understand what the accepted answer said and I don't think it was even the question I am asking here.

Community
  • 1
  • 1
randers
  • 5,031
  • 5
  • 37
  • 64
  • 2
    _This gives a error._ Do we guess? – Sotirios Delimanolis Jan 19 '15 at 17:23
  • When the actual type parameter is `?`, it stands for some `unknown type`.As here you know all bean extends `SuperClass` so you don't need `?` here. direct use `SuperClass` instead of '? extends SuperClass` – bNd Jan 19 '15 at 17:32
  • Everybody is answering this question seems to be assuming Generic Constraints do not exist and there's no reason why one would need them. Seriously, if they don't exist in Java than tell him, but don't assume he's asking for something stupid because Java doesn't have it. – Joshua Jan 19 '15 at 18:50
  • @Joshua It's not obvious to me that the OP actually wants what you seem to think they want, in terms of getting out a specific subclass of `myClass`. – Louis Wasserman Jan 20 '15 at 00:22

3 Answers3

2

You do not need to use ?. Generics are not used like that except in rare (and usually strange) circumstances.

class MyClass {

}
class MyExtendedClass extends MyClass {

}
public void test() {
    Map<Integer, MyClass> myMap = new HashMap<Integer, MyClass>();
    myMap.put(1, new MyClass());
    myMap.put(2, new MyExtendedClass());
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
0

This is really just a

public HashMap<Integer, myClass> myMap = new HashMap<Integer, myClass>();

Which will, as requested, accept subtypes of myClass.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
-1

try:

public HashMap<Integer, myClass> myMap = new HashMap<Integer,myClass>();
Igor Zelaya
  • 4,167
  • 4
  • 35
  • 52
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – msrd0 Jan 19 '15 at 18:58