user2763361
user2763361

Reputation: 3919

How to get a map of interfaces or superclasses in java

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?

Upvotes: 0

Views: 199

Answers (1)

Braj
Braj

Reputation: 46841

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

Upvotes: 1

Related Questions