0

I'm trying to implement binary search tree in java. It can take any object as the data of a node in the tree, as long as that object implements the Comparable interface. This is needed because while putting a new node in the tree, we need to decide, whether the new node is of lesser or greater value compared to its parent. My Node class looks something like the following.

package com.java.ds.bst;

public class Node<T extends Comparable<T>> implements Comparable<T> {
  private T data;
  private Node<T> left = null;
  private Node<T> right = null;

  public Node() {
    this.data = null;
  }

  public Node(T data) {
    this.data = data;
  }

  public T getValue() {
    return this.data;
  }

  public Node<T> getLeft() {
    return this.left;
  }

  public Node<T> getRight() {
    return this.right;
  }

  public void setLeft(Node<T> left) {
    this.left = left;
  }

  public void setRight(Node<T> right) {
    this.right = right;
  }

  @Override
  public int compareTo(T other) {
    return this.data.compareTo(other);
  }
}

What I don't understand is, in the class name declaration, why do I need T extends Comparable<T> instead of T implements Comparable<T>?

Bitswazsky
  • 4,242
  • 3
  • 29
  • 58
  • that's the syntax for generic type bounds. `extends` in this context stands for either "extends a class" or "implements an interface" – Eran Jan 09 '19 at 10:38
  • 1
    The linked duplicate explains generic type bounds. The `extends` keyword means different things in different contexts. You are correct that a class `implement`s an interface, just as your Node does, but a generic type bound does not distinguish between an extending and implementing relationship (because it's not useful to do so). – Michael Jan 09 '19 at 10:42
  • @Michael That explains it I guess. Thanks. – Bitswazsky Jan 09 '19 at 10:49

1 Answers1

1

It is the syntax for generics, T extends Comparable<T> means it will accept anything that is Comparable<T>.

You are correct to use implements Comparable<T> when implementing the interface.

Daniel B.
  • 2,491
  • 2
  • 12
  • 23