Generics Compile Problem

P

petek1976

Can anyone tell me why this code will not compile? I'm only including
the relevant portions of the code. I don't understand the error from
the compiler:

public class Msg
{
}

public interface MsgListener<T>
{
public void Process(T msg);
}

import java.util.*;
public class MsgRegistration
{
private HashMap<String,MsgListener<? extends Msg>> mcMap = new
HashMap<String,MsgListener<? extends Msg>>();

public <X extends Msg> void doit(String acName, X acMsg)
{
MsgListener<? extends Msg> lcListener= mcMap.get(acName);
lcListener.Process(acMsg);
}

}

MsgRegistration.java:10: Process(capture of ? extends Msg) in
MsgListener<capture of ? extends Msg> cannot be applied to (X)
lcListener.Process(acMsg);

Why can't it be applied to X since X extends Msg?
 
D

Daniel Pitts

petek1976 said:
Can anyone tell me why this code will not compile? I'm only including
the relevant portions of the code. I don't understand the error from
the compiler:

public class Msg
{
}

public interface MsgListener<T>
{
public void Process(T msg);
}

import java.util.*;
public class MsgRegistration
{
private HashMap<String,MsgListener<? extends Msg>> mcMap = new
HashMap<String,MsgListener<? extends Msg>>();

public <X extends Msg> void doit(String acName, X acMsg)
{
MsgListener<? extends Msg> lcListener= mcMap.get(acName);
lcListener.Process(acMsg);
}

}

MsgRegistration.java:10: Process(capture of ? extends Msg) in
MsgListener<capture of ? extends Msg> cannot be applied to (X)
lcListener.Process(acMsg);

Why can't it be applied to X since X extends Msg?

The problem is that "lcListener" is of type "? extends Msg", which
might mean its a "Y" which extends Msg. X objects wouldn't be valid in
that case...
What you want is MsgListener<Msg>
Actually, it looks like you don't even want generics in this case. if X
is a subclass of Msg, you can just use polymorphism.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top