0

Suppose I have interface (or superclass, doesn't matter) Program and implementation Firefox. I would like to define a map in some classes state as Map<Long,Program> mapOfPrograms then in a setter set mapOfPrograms = new TreeMap<Long,Firefox>(); through dependency injection. I need to be able to do mapOfPrograms.put(1l,new Firefox()); or mapOfPrograms.put(1l,(Program)(new Firefox())); I then need to be able to get and use these objects.

I'm getting the error Type Mismatch: cannot convert from Map<Long,Program> to TreeMap<Long,Firefox>. Doesn't matter if Program is an interface or superclass.

How do I overcome this issue?

user2763361
  • 3,789
  • 11
  • 45
  • 81

1 Answers1

1

Try this one

class MyMap<K,T extends Program> extends TreeMap<K,Program>{

    private static final long serialVersionUID = 1L;

}

interface Program{

}

class Firefox implements Program{

}

And here is your code

    Map<Long, Program> map=new MyMap<Long,Firefox>();
    map.put(1L, new Firefox());
Braj
  • 46,415
  • 5
  • 60
  • 76
  • You can define keys other than `Long` as `MyMap` is parametrized. – Braj Apr 05 '14 at 14:38
  • +1, will this solution allow me to get as well as put like normal? Why wouldn't I use `? super` ? – user2763361 Apr 05 '14 at 14:41
  • Find the solution here [java generics super vs. extends](http://stackoverflow.com/questions/13133714/java-generics-super-vs-extends?answertab=votes#tab-top). – Braj Apr 05 '14 at 14:44