Java : How do I implement a generic Binary Search Tree?

daydreamer picture daydreamer · Jun 29, 2012 · Viewed 27.9k times · Source

Until now, I have been writing a Node class as

class Node {
        private  value;
        private Node left;
        private Node right;

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public Node getLeft() {
            return left;
        }

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

        public Node getRight() {
            return right;
        }

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

and Binary Search Tree as

public class BinarySearchTree {
    private Node root;

    public BinarySearchTree(int value) {
        root = new Node(value);
    }

    public void insert(int value) {
      Node node = new Node(value);
        // insert logic goes here to search and insert
    }
}

Now I would like to support BinarySearchTree to have insert node of any type like strings, people

How can I make it generic to hold any type?

Answer

Petar Minchev picture Petar Minchev · Jun 29, 2012

Use generics:

class Node<T extends Comparable<T>> {
        private T value;
        ...
}

public class BinarySearchTree<T extends Comparable<T>> {
    private Node<T> root;

    public BinarySearchTree(T value) {
        root = new Node<T>(value);
    }

    public void insert(T value) {
      Node<T> node = new Node<T>(value);
        // insert logic goes here to search and insert
    }
}