سؤال

I am trying to extend a version of TreeMap into a subclass to index words more efficiently, but I am unsure what the correct syntax is. The class definition for the treemap looks like this

public class MyTreeMap<K extends Comparable<? super K>,V> extends AbstractMap<K,V> {

Extending the class in the most straightforward way

public class TreeMapIndexer<K> extends MyTreeMap<K,LinkedList<Integer>> {

yields the error "Bound mismatch: The type K is not a valid substitute for the bounded parameter > of the type MyTreeMap".

I tried

public class TreeMapIndexer<K> extends 
MyTreeMap<K extends Comparable<? super K>, LinkedList<Integer>> {

instead, but that yields the compiler error "Syntax error on token "extends", , expected". The erroneous extends is in the "".

I found another thread (Generic Generics: "Syntax error on token "extends", , expected") with the same error message. It appears to be a slightly different situation than mine, but I tried

public class TreeMapIndexer<K> extends 
MyTreeMap<K, K extends Comparable<? super K>, LinkedList<Integer>> {

which yields exactly the same "Syntax error on token "extends", , expected" compiler message.

هل كانت مفيدة؟

المحلول

class MyTreeMap<K extends Comparable<? super K>, V>
extends AbstractMap<K, V>

So K is declared with a bound of extends Comparable<? super K>. You just need to redeclare that same bound on the subclass.

class TreeMapIndexer<K extends Comparable<? super K>>
extends MyTreeMap<K, LinkedList<Integer>>

Otherwise you are attempting to declare the subtype as not having the restriction which is the compilation error 'bound mismatch'.

What you tried was almost right, the bound just needed to be in the generic type declaration, not the arguments (passed along) to the superclass.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top