Given a KeyHolder interface such as the following:
public interface KeyHolder<K extends Key> {
K getKey();
}
I’d like to create a class like this:
public KeyHolderSet<H extends KeyHolder<K extends Key>> extends HashSet<H> {
public Set<K> getKeySet() {
Set<K> keySet = new HashSet<K>();
for (H keyHolder : this) {
keySet.add(keyHolder.getKey());
}
return keySet;
}
}
But that doesn’t work, the closest I can get is this:
public KeyHolderSet<H extends KeyHolder<? extends Key>> extends HashSet<H> {
public <K extends Key> Set<K> getKeySet() {
Set<K> keySet = new HashSet<K>();
for (H keyHolder : this) {
// Explicit cast to K
keySet.add((K)keyHolder.getKey());
}
return keySet;
}
}
Any way around this?
You need to write it like this:
Unfortunately you will have to declare the type of K first and it cannot be inferred.