2

how do I correctly write following class declaration in Java?

public class BinarySearchTree<T extends BinarySearchNode<E implements Comparable<E>>> implements Iterable<E>

Basically, I am trying to create a BinarySearchTree of any class T that inherits BinarySearchNode of a Comparable datatype E (And my BinarySearchTree should also be Iterable).

How can I properly declare that class in Java? Thanks!

9
  • 1
    Why does this thing take the node type instead of the element type as a type parameter? Commented May 8, 2017 at 16:49
  • 1
    SIde question... Shouldn't your class be Iterable on the values i.e. E instead of on the node? Commented May 8, 2017 at 19:24
  • 1
    @FedericoPeraltaSchaffner that's a good question! In fact I agree with you, will edit the question. Thanks! Commented May 8, 2017 at 19:27
  • 1
    Another suggestion... I would change E extends Comparable<E> for E extends Comparable<? super E>. This would allow you to have a tree of i.e. Dog with Dog being a subclass of Animal and Animal being Comparable. I mean that you could use the compareTo method from one ancestor of the element type of your tree, and you shouldn't need to implement compareTo in Dog (using the one from Animal would suffice, if it's good enough). Commented May 8, 2017 at 20:21
  • 1
    All this with that only change from <E> to <? super E>. If you are interested on this topic, you should read about PECS. Commented May 8, 2017 at 20:21

2 Answers 2

2
public class BinarySearchTree<T extends BinarySearchNode<E>, E extends Comparable<E>> implements Iterable<E>

The type parameter E needs to be defined separately from the node type, even if it ends up looking redundant: BinarySearchTree<BinarySearchNode<String>, String>. Java won't let you directly access a generic parameter of a generic type.

Also, note that generic parameters always use "extends" even with interfaces.

Sign up to request clarification or add additional context in comments.

Comments

0

With Generics in Java, you will only use extends. So, essentially your method decoration would become:

public class BinarySearchTree<T extends BinarySearchNode<E extends Comparable<E>>> extends Iterable<T>

Even for those classes that implement an interface, generics will use extends. The only other syntax for generics is super if you are looking at the inheritance from the opposite direction

1 Comment

This does not compile. You cannot nest generics' extends in a class definition, i.e. you cannot have class A<T extends B<E extends C>>. Besides, Iterable is an interface, so you must use the keyword implements if the class acutally implements it, it cannot be extended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.