简体   繁体   中英

Bound mismatch: The type is not a valid substitute for the bounded parameter

I've recently started implementing a few data structures and, well, I am trying to make everything as 'extensible' as possible.

public abstract class AbstractNode<E extends Element, U extends AbstractNode<E, U>> { ... }

public class BinarySearchTree<Element> extends Tree<Element, Node<Element>> { ... }

public class Element implements Cloneable { ... }

public class Node<E extends Element> extends AbstractNode<E, Node<E>> { ... }

public abstract class Tree<E extends Element, T extends AbstractNode<E, T>> { ... }

I am getting a lot of errors in the BinarySearchTree class with the message Bound mismatch: The type Element is not a valid substitute for the bounded parameter <E extends Element> of the type Node<E> . Why!? What am I doing wrong there?

Also, in the BinarySearchTree class I am getting a The type parameter Element is hiding the type Element right in BinarySearchTree<Element> .

Ty for the help!

The definition of your BinarySearchTree is:

public class BinarySearchTree<Element> extends Tree<Element, Node<Element>>

Here, Element is a type-parameter, but not the actual type Element . It's pretty much the same, as you did:

public class BinarySearchTree<T> extends Tree<T, Node<T>>

Now the error you're getting makes more sense:

The type T is not a valid substitute for the bounded parameter <T extends Element> of the type Node<T>

This is reasonable, because the parameter T doesn't have an upper bound Element , which is required by the definition of Node . This can be easily fixed with:

public class BinarySearchTree<T extends Element> extends Tree<T, Node<T>>

Note that here, the upper-bound is not a type-parameter, but an actual type ( Element ).

As a rule of thumb, you should avoid naming your type-parameters like existing types, because a lot of confusion can happen. The type-parameters names usually consist of a single, upper-cased letter. If you follow this practice, it would be very, very difficult to end up with similar issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM