Search code examples
javacollectionsbinary-search-treecomparabletreeset

add objects to Binary Search tree using custom comparator?


I need to add objects to the Binary search tree and want to write my own compareTo method. How should i go about this. Actually i am trying to implement a custom TreeSet. I am confused where to implement a comparator or comparable and define it. Any help appreciated


Solution

  • Your object must be implements interface Comparable

    class MyClass implements Comparable { 
      int compareTo(){...}
    }
    final Set set = new TreeSet();
    set.add(new MyClass());
    ....
    set.add(new MyClass());
    

    or make our own comparator:

    class MyClass {}
    
    class MyComparator implements Comparator {
        int compareTo(Object o1, Object o2){
          ...
        }
    }
    final Set set = new TreeSet(new MyComparator());
    set.add(new MyClass());
    ....
    set.add(new MyClass());