0
public class Declaration {}

public class Class_object extends Declaration{}

above is my class declaration, so basically Class_object is subclass of class Declaration.

    Map<String,ArrayList<Declaration>> structure = new HashMap<String,ArrayList<Declaration>>();
    ArrayList<Class_object> co = new ArrayList<Class_object>();
    structure.put("CLASS", co);//here gives error:The method put(String, ArrayList<Declaration>) in the type Map<String,ArrayList<Declaration>> is not applicable for the arguments (String, ArrayList<Class_object>)

In another class, I try to create a hashmap to contain different subclasses of Declaration, but it gives me error message. Could anyone tell me how to fix it?

BroLegend
  • 59
  • 6

2 Answers2

1

Generics are invariant. You could do

Map<String, List<? extends Declaration>> structure 
            = new HashMap<String, List<? extends Declaration>>();
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

You will have to use the extends keyword to be able to put subclasses of Declaration in your map. Define it like so:

Map<String,ArrayList<? extends Declaration>> structure = new HashMap<String,ArrayList<? extends Declaration>>();

? extends Declaration lets java know that you want to be able to use use any classes that extend Declaration, such as Class_object.

gla3dr
  • 2,179
  • 16
  • 29