Problem With Java Generic Interface passed to Generic Constructor
I have an interface and a class and both compile just fine. But when I try to instantiate a Separator with an anonymous implementation of Namer It fails to compile.
private interface Namer<N>
{
String getName(N o);
};
private static class Separator<H>
{
HashSet<H> oldDiff;
HashMap<String, H> newFaMap;
public Separator(HashSet<H> older, HashSet<H> newer, Namer<H> namer)
{
oldDiff = new HashSet<H> (older);
HashSet<H> newDiff = new HashSet<H> (newer);
oldDiff.removeAll(newer);
newDiff.removeAll(older);
newFaMap = makeMap(newDiff, namer);
}
private HashMap<String, H> makeMap(HashSet<H> set, Namer<H> namer)
{
HashMap<String, H> map = new HashMap<String, H>();
for (H holder : set)
{
map.put(namer.getName(holder)开发者_如何学编程, holder);
}
return map;
}
}
in a method
Namer<FAHolder> namer = new Namer<FAHolder>() {
public String getName(FAHolder o)
{
return o.getName();
}
};
new Separator<FAHolder>(older, newer, namer);
The compile error is:
The constructor
MyClass.Separator<FAHolder>(Set<FAHolder>, Set<FAHolder>, MyClass.Namer<FAHolder>)
is undefined
What have I overlooked?
It looks like the static type of older
and newer
is Set<FAHolder>
and not HashSet<FAHolder>
. Change your constructor's signature from:
public Separator(HashSet<H> older, HashSet<H> newer, Namer<H> namer)
to
public Separator(Set<H> older, Set<H> newer, Namer<H> namer)
I do not know the declaration of older
and newer
in the constructor calling code, but why you use HashSet
instead of Set
in the Separator
class? Maybe older
and newer
are declared as Set
?
Your older and newer objects seem to be of type "Set" while your constructor parameters are "HashSet".
精彩评论