Search code examples
javadata-structuresgeneric-programming

generic programming, generic data structures


I am trying to implement a Binary Search Tree and if I use the generic programming in java then this tree should be able to store any kind of data e.g. int, Strings or basically any other object. But the problem with such a class is with coding the functions e.g. if I am coding the addToTree function, then "<" operator can be used to compare int and it would successfully insert int into the tree but it won't insert strings or other objects because comparing strings and other objects using "<" operator may not be allowed.

This problem is same for other data structures too.


Solution

  • You should limit the generic type for your BinarySearchTree,

    class BinarySearchTree<T extends Comparable<? super T>>
    

    The element should implement Comparable interface, otherwise you are not able to order the elements.

    Edit: As @JB Nizet suggests, don't use raw Comparable