, KeyHolder<K extends Key> KeyHolderSet<H extends KeyHolder<K extends Key>> :
public class KeyHolderSet<H extends KeyHolder<?>>
.
Edit: I see your problem with getKeySet(). This method should return H instead of K. H will print with what you entered in the KeyHolderSet declaration (Variabe, not the class).
public class KeyHolderSet<H extends KeyHolder<?>> extends HashSet<H> {
private H theKeySet;
public void setKeySet(H keyset) {
theKeySet = keyset;
}
public H getKeySet() {
return theKeySet;
}
}
-
class betterKey extends Key {
}
-
public static void main(String[] args) {
KeyHolder<betterKey> kh = new KeyHolder<betterKey>() {
};
KeyHolderSet<KeyHolder<betterKey>> khs = new KeyHolderSet<KeyHolder<betterKey>>();
khs.setKeySet(kh);
KeyHolder<Key> kh2 = khs.getKeySet();
}
As you can see, khs.getKeySet()returns KeyHolder<betterKey>as expected.
Edit2: You can create a set outside of the KeyHolderSet class:
public static void main(String[] args) {
KeyHolderSet<KeyHolder<betterKey>> khs = new KeyHolderSet<KeyHolder<betterKey>>();
Set<betterKey> bks = new HashSet<betterKey>();
for (KeyHolder<betterKey> kh : khs) {
bks.add(kh.getKey());
}
}
One alternative solution that I came up with is returning a completely general set, remember that all type checking will be lost in this way.
public class KeyHolderSet<H extends KeyHolder<?>> extends HashSet<H> {
public <K extends Key> Set<K> getKeySet() {
Set<K> s = new HashSet<K>();
for (H keyHolder : this) {
s.add((K) keyHolder.getKey());
}
return s;
}
public static void main(String[] args) {
KeyHolderSet<KeyHolder<betterKey>> khs = new KeyHolderSet<KeyHolder<betterKey>>();
Set<Key> ks = khs.getKeySet();
Set<betterKey> bks = khs.getKeySet();
Set<evenBetterKey> ss = khs.getKeySet();
}
}
class betterKey implements Key {
}
class evenBetterKey extends betterKey {
}
Dorus source
share