Implementing comparable for a TreeMap

I'm trying to create a League of Players which is ordered by the player grade, but the comparism method (compareTo) doesn't seem to be getting called. The following list should be displayed in grade order
RANK LIST
950 Alactaga
1000 Aragorn
1000 Black Jack II
950 Brius
1100 Fitzchev
1150 Heraldo
950 Horace
900 Killer Giraffe
I have 3 main classes involved: Player, Players, League
public class Player implements Comparable {
     private static final int START_GRADE = 1000;
     private String name;
     private int grade;
      * Constructor
      * Note that the constructor is private to ensure that
      * only one unique version of each player can exist.
     private Player(String name) {
          this.name = name;
          this.grade = START_GRADE;
     public int compareTo(Object o) {
               System.out.println("Comparing!!");
             Player n = (Player)o;
             int gradeComp = new Integer(grade).compareTo(new Integer(n.grade));
             return gradeComp;
      * Factory method for creating a new player
     public static Player create(String name) {
          return new Player(name);
public class Players extends TreeMap {
      * Constructor
     public Players() {
          loadPlayers();
      * Load the players
      * These could come from a file or a database.
     private void loadPlayers() {
          // Some hard-coded stuff for testing
          this.put("Black Jack II", Player.create("Black Jack II"));
          this.put("Fitzchev", Player.create("Fitzchev"));
          this.put("Brius", Player.create("Brius"));
     public Player getNamed(String name) {
          return (Player) get(name);
public class League extends Players {
     private static final int DELTA = 50;
      * Main routine for recalculating rankings based on a given game
     public void scoreGame(Game game) {
     }I followed the following tutorial item to get me started:
http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
Thanks for any help!

Thanks for the help. The toString() function of the League class now begins as follows:
      * Create a string version of the ranked list
     public String toString() {
          String rankListString = "";
          rankListString += "RANK LIST\n";
          rankListString += "---------\n";
          Collection players = this.values();
          Players[] playersArray = (Players[]) players.toArray();
          Comparator myComparator = new Comparator() {
               public int compare(Object o1, Object o2) {
                    int comp;
                    System.out.println("Comparing!!");
                    Player p1 = (Player)o1;
                    Player p2 = (Player)o2;
                    if (p1.getGrade() < p2.getGrade()) {
                         comp = -1;     
                    else if (p1.getGrade() > p2.getGrade()) {
                         comp = 1;
                    else {
                         comp = 0;
                    return comp;
          Arrays.sort(playersArray, myComparator);At the moment though I have a ClassCastException on the following line:
Players[] playersArray = (Players[]) players.toArray();          java.lang.ClassCastException
     at core.League.toString(League.java:65)
     at java.lang.String.valueOf(Unknown Source)
     at java.io.PrintStream.print(Unknown Source)
     at java.io.PrintStream.println(Unknown Source)
     at main.Grape.main(Grape.java:37)
Exception in thread "main"
I'm still a bit of a newbie as you can see. Any help would be appreciated. Thanks!

Similar Messages

  • Implementing Comparable for multiple types

    I am currently refactoring some legacy code to make use of Java 5's generics, and I ran into a problem.
    Foo extends Parent and implements Comparable. Bar is a sibling of Foo and does not implement Comparable. Now, in the legacy code, Foo is Comparable to both Foo and Bar, and in order to use generics, I have to specify a single class or use wild cards with "extends". I know I could resolve this problem by using <? extends Parent>, but I am reluctant to do this, because Foo and Bar also have about 30 other siblings.
    Is there anyway that I can use generics and only let the two classes, Foo and Bar be Comparable to Foo?

    I quite don't get what the legacy code does. If Bar does not implement comparable, how is Foo comparable to Bar? I think, this quite violates the rules for implementing Comparable.
    You don't have to implement an additional class, though, but might work with an interface, which both Foo and Bar implement and which extends Comparable on the interface.
    Maybe I should give an abstract example on my confusing statement. :)
    interface FooBar extends Comparable<FooBar> { ...}
    class Foo implements FooBar { ... }
    class Bar implements FooBar { ... }

  • Comparator for TreeMap Integer[], Double

    Hi all,
    I'm trying to write a compartor for a TreeMap<Integer[], Double>. The Integer[] has always two entries and [x,y] should be equal to [y,x].
    This is my code:
    TreeMap<Integer[], Double> t = new TreeMap<Integer[], Double>(new Comparator(){
                public int compare(Object o1, Object o2) {
                    Integer[] i1 = (Integer[]) o1;
                    Integer[] i2 = (Integer[]) o2;
                    if (i1[0].equals(i2[0]) && i1[1].equals(i2[1]))
                        return 0;
                    if (!i1[0].equals(i2[0]))
                        return i1[0].compareTo(i2[0]);
                    return i1[1].compareTo(i2[1]);
            });However, after inserting two elements like
    t.put(new Integer[]{1,2}, 0.1);
    t.put(new Integer[]{2,1}, 0.2);, the TreeMap contains these two elements instead of just one.
    Is there an error in my Comparator?
    Regards,
    Andreas

    the two elements are inside your map because their keys new Integer[]{1,2} and new Integer[]{2,1} are different, so they represent different values.
    To make this simpler, one possibility is to create a wrapper class for these two integers, and override equals()

  • Comparator to a TreeMap

    Hi
    I insert to a TreeMap (kays,values) where the values contains a custom class.in the constructor of TreeMap I want to insert a comparator wich will sort the records by a variable of the custom class I made. How can I do it?
    my custom class
    public class DrawRecord {
      int id = 0;
      String date = "";
      int drawNum = 0;
      String result = "";
      String winner = "";
      public DrawRecord(String date, int drawNum, String result, String winner) {
        this.id = id;
        this.date = date;
        this.drawNum = drawNum;
        this.result = result;
        this.winner = winner;
      public int getDrawNumber() {
        return drawNum;
    }the main class portion:
    TreeMap treemap = TreeMap(new ItemComparator())
      treemap.add(key,value);the comperator as my question:
    class ItemComparator implements Comparator {
      public int compare(Object o1, Object o2) {
          if ( ( ( ? ) o1).itemRecord.drawNum  < ( ( ? ) o2). itemRecord.drawNum  {
              return 1;
          if ( ( ( ? ) o1). itemRecord.drawNum  == ( ( ? ) o2).itemRecord.drawNum  (){
              return 0;
          return -1;
      public boolean equals(Object obj) {
          return obj instanceof ItemComparator;
    }Thanks
    D

    * You can provide a Comparator that just reversesthe
    order of what Date's compareTo function does.
    Collections.reverseOrder() may (or may not) help you
    here.
    i got the idea but can i implement it by code? No, you implement it by stuffing Ricky Martin's toenail clippings up your nose while warming an egg salad sandwich under your left armpit (make sure it's the left--the right implements belly button locusts) and doing an imitation of Leonard Nimoy singing "Fat Bottomed Girls". On a Tuesday.
    (dont
    write for me the code just give me a way to go)Well, I haven't looked at that reverseOrder at all, but what I'd do if I were going to write my own comparator is this:
    Comparator.compare takes two objects, compares them, and returns negative, zero, or positive, depending if the first object is, respectively, less than, equal to, or greater than the second.
    Now, what we want is, given two Dates, d1 and d2, we want ourComparator.compare(d1, d2) to return the opposite of what d1.compareTo(d2) would.
    So you cast both of compare's args to Dates, and then return the aforementioned opposite. (Actually, this would work for any Comparable, so you can just cast them to Comparable.)
    Do you think you can get it from that? Because I don't know what other hints I can give you that don't basically amount to writing the code for you.
    &para;

  • Comparator for non-standard alphabetical sorting

    Dear all,
    Default String.compareTo() method doesn't satisfy me -- alphabetical order of Latvian is slightly different from that in Unicode charts. I'm using TreeMap for indexation purposes so I implemented my own Comparator (LatvianStringComparator) to achieve correct sorting.
    Initialisation of the index is as follows:
    SortedMap index = new TreeMap(new LatvianStringComparator());Implementation of LatvianStringComparator:
    import java.io.Serializable;
    import java.util.Comparator;
    public class LatvianStringComparator implements Comparator, Serializable {
         public static final String SORT_ORDER = "a&#257;bc&#269;de&#275;fg&#291;hi&#299;jk&#311;l&#316;mn&#326;oprs�tu&#363;vz�";
         public int compare(Object o1, Object o2) {
              if (!(o1 instanceof String) || !(o2 instanceof String)) {
                   throw new ClassCastException();
              String str1 = (String)o1;
              String str2 = (String)o2;
              //Case 1: strings are equal.
              if (str1.equals(str2)) return 0;
              //Case 2: strings have to be compared char by char.
              //By default the first string is "less than" the second one.
              int signum = -1;
              int polarity = 1;
              int str1Rank = -1;
              int str2Rank = -1;
              if (str2.length() < str1.length()) {
                   //Primary string is the shortest one; polarity changes.
                   String temp = str1;
                   str1 = str2;
                   str2 = temp;
                   polarity = -1;
              for (int i = 0; i < str1.length(); i++) {
                   str1Rank = SORT_ORDER.indexOf(str1.charAt(i));
                   str2Rank = SORT_ORDER.indexOf(str2.charAt(i));
                   //If char is not present in the specified alphabeth,
                   //it's Unicode position is taken; SORT_ORDER.length() = offset.
                   if (str1Rank == -1) {
                        str1Rank = str1.charAt(i) + SORT_ORDER.length();
                   if (str2Rank == -1) {
                        str2Rank = str2.charAt(i) + SORT_ORDER.length();
                   if (str2Rank < str1Rank) {
                        //First string is "greater than" the second one.
                        signum = 1;
                        break;
              return signum * polarity;
    PROBLEM:
    For small set of keys (tested on several elements) sorting seems to work well, but in case of large number of keys (> 10K) order is strange and fragmented. I'm sure that the problem is not in the number of keys.
    Another issue: many values for keys appear as null!
    If I remove new LatvianStringComparator() from the param list of TreeMap constructor, my app works fine except the sorting according the Latvian alphabeth. So I asume that my implementation of Comparator is erroneous or I have misunderstood something conceptually.
    Could anybody inspect the code, please? THANK YOU!!!
    Normunds

    Hi,
    even this small code fails:
            SortedMap index = new TreeMap(new LatvianStringComparator());
            index.put("baa", "baa");
            index.put("aaa", "aaa");
            index.put("aqa", "aqa");
            index.put("caa", "caa");
            Iterator it = index.keySet().iterator();
            while (it.hasNext()) {
                String key = (String)it.next();
                System.out.println(key);
            }because you assume '...first string is "less than" the second one'
    but you did not test it.
    Just add a 'less test' like:
    if (str2Rank > str1Rank) {
    //First string is "less than" the second one.
    signum = -1;
    break;
    }after
    if (str2Rank > str1Rank) {}and your code will work.
    even better: use Collator API
    Franco

  • Implementing Comparable in an abstract class

    Hi all,
    I am making my first sortie with abstract classes. I have had a good look around, but would still appreciate some advice with the following problem.
    In my application I have several classes that have many things in common. I have concluded therefore, that if I create and then inherit from an abstract super class, I can reduce and improve my code. I created this abstract class:
    public abstract class YAbstractObject implements Comparable {
        public YAbstractObject(int projectId, YObject object, String objectName) {
            this.projectId = projectId; // Always the same parameters
            this.object = object;
            this.objectName = objectName;
        // This is abstract as it must always be present for sub classes but differant processing will take place
        public abstract void resolveObject();
        // These three methods will always be the same for all sub classes
        public String getName() {
            return objectName;
        public YObject getObject() {
            return object;
        public boolean isValid() {
            return isValid;
    // Overridden and always the same for all sub classes
        public String toString() {
            return objectName;
        // implemented abstract method
        public int compareTo(Object thatObject) {
            // Issue here! I would like something as follows:
            //  return this.getName().compareToIgnoreCase(thatObject.getName());
    // Variable decleration
        private int projectId;
        private YObject object;
        private String objectName;
        private boolean isValid;As I have commented in the compareTo() method, I would like it to be able to use the getName() method for comparison objects and compare them. But it does not like this, as it does not know that "thatObject" is of the same class as this object - I hope that made sense.
    in essence, I want to inherit this method for different classes and have it work with each.
    Is there a way to do this? Generics?
    Any observations, greatly appreciated,
    Steve

    You can use also generics (if applicable: java -version >= 1.5).
    public abstract class Test implements Comparable<Test> {
         String name;
         public Test(String name) {
              this.name = name;
         public String getName() {
              return name;
         public int compareTo(Test obj) {
              return this.getName().compareTo(obj.getName());
    public class Other extends Test {
         public Other(String name) {
              super(name);
    public class Tester extends Test {
         public Tester(String name) {
              super(name);
         public static void main(String[] args) {
              Test t = new Tester("t");
              Test a = new Tester("a");
              Test o = new Other("t");
              System.out.println(t.compareTo(a));
              System.out.println(t.compareTo(new Object())); //compile error
              System.out.println(t.compareTo(o));
    }Without the compile error line it will give the following result:
    19
    0

  • Comparator for different classes

    I have a crazy need to be able to hold a few hundred thousand objects in a Set. These objects can vary from Integers, Doubles to Strings. Normally it seems a HashSet would be the perfect implementation for this, however, this Set is built once and searched through several million times. So it makes sense to have a SortedSet available for this to improve search times. Having different sets for each Class type is not an option.
    I've come up with this code, which works fairly well as far as I can tell, but would like your general opinions on how it can be improved. I can't find a failing point, yet, and would like the eyes of many to tell me that I'm wrong - and that it can fail somehow.
    public class DifferentObjectComparator implements Comparator, Serializable
         public int compare(Object o1, Object o2)
              if (o1 == null && o2 == null) return 0;
              if (o1 == null && o2 != null) return 1;
              if (o1 != null && o2 == null) return -1;
              if (o1.getClass() == o2.getClass())
                   return ((Comparable) o1).compareTo(o2);
              if (o1 instanceof Number && o2 instanceof Number)
                   double retVal = ((Number) o1).doubleValue() - ((Number) o2).doubleValue();
                   if (retVal < 0) return -1;
                   if (retVal > 0) return 1;
                   return 0;
              return -1;
    }If you know of and/or can think of a better way to do this, please tell. Keep in mind it must use a SortedSet implementation.

    cvweiss__ wrote:
    After a couple of tweaks and some extensive testing I am now satisfied that the following code fully complies with the specifications given in the javadoc for java.util.Comparator. I'm posting this here for those in the future who have this requirement.
    public class DifferentObjectComparator implements Comparator, Serializable
         public int compare(Object o1, Object o2)
              if (o1 == o2) return 0; // good for two nulls or exact same Object
              if (o1 == null && o2 != null) return 1;
              if (o1 != null && o2 == null) return -1;
              if (o1.getClass() == o2.getClass())
                   return ((Comparable) o1).compareTo(o2);
              if (o1 instanceof Number && o2 instanceof Number)
                   double retVal = ((Number) o1).doubleValue() - ((Number) o2).doubleValue();
                   if (retVal < 0) return -1;
                   if (retVal > 0) return 1;
                   return 0;
              return o1.getClass().getName().compareTo(o2.getClass().getName());
    if they ALL implements Comparable, wouldn't the Set be
    Set<? extends Comparable> theSet;? In which case, the Comparator could be more elegantly written using similar generics, like
    public class MyComparator implements Comparator<Comparable> {
      public int compare(Comparable c1, Comparable c2) {
                  if (c1 == c2) return 0;
              if (c1 == null && c2 != null) return 1;
              if (c1 != null && c2 == null) return -1;
              if (c1.getClass() == c2.getClass())
                   return c1.compareTo(c2);
              if (c1 instanceof Number && c2 instanceof Number)
                   double retVal = ((Number) c1).doubleValue() - ((Number) c2).doubleValue();
                   if (retVal < 0) return -1;
                   if (retVal > 0) return 1;
                   return 0;
              return c1.getClass().getName().compareTo(c2.getClass().getName());   // looks weird to me
    }no more ugly castings! (well, except for casting to Number, but that's inherent to the weird spec to begin with)

  • Compare date with implements Comparator

    I have a DefaultListModel (mode) staffed with EMPL (id, name, startingDate). I would like to sort the defaultListModel accourding to the dob. for this I do the following:
                   Object[] contents = model.toArray();               
                   Arrays.sort(contents, new ComparatorDate());
                   model.copyInto(contents);the comparator: ComparatorDate
    public class ComparatorDate implements Comparator
         public int compare(Object o1, Object o2)
              Empl a = (Empl ) o1;
              Empl b = (Empl ) o2;
              Date d1 = a.getStartDate();
              Date d2 = b.getStartDate();
              return (d1.getDate()-d2.getDate());
    }when debugging I realize the dates are diff but the d1.getDate()=1 and d2.getDate()=1 ??? how come? the result are not what expected.
    any idea?

    getDate() tells you the day of the month. Both your dates are apparently on the first of some month. Since Date implements Comparable, why not just do return d1.compareTo(d2)

  • Why does not Boolean implement Comparable? (at least in JDK 1.4)

    OK, I have read JDK 1.5.0 Beta 2 docs and learned that now java.lang.Boolean implements Comparable<Boolean>.
    But why it was not noticed until 1.5?
    I can guess that Boolean is not as used as another wrapper classes, and implementing the Comparable interface was not heavily demanded (for instance, requiring a JSR or 500 votes in the Bug Database).
    But even Google's Joshua Bloch could have noticed it before...

    Additional info from the API v1.4.2:
    public interface Comparable
    It is strongly recommended (though not required) that natural orderings be consistent with
    equals. This is so because sorted sets (and sorted maps) without explicit comparators
    behave "strangely" when they are used with elements (or keys) whose natural ordering is
    inconsistent with equals. In particular, such a sorted set (or sorted map) violates the gen-
    eral contract for set (or map), which is defined in terms of the equals method.
    For example, if one adds two keys a and b such that
    (!a.equals((Object)b) && a.compareTo((Object)b) == 0)
    to a sorted set that does not use an explicit comparator, the second add operation returns
    false (and the size of the sorted set does not increase) because a and b are equivalent from
    the sorted set's perspective.
    Boolean equals
      public boolean equals(Object obj)
    Returns true if and only if the argument is not null and is a Boolean object that represents
    the same boolean value as this object.
    Boolean hashCode
      public int hashCode()
    Returns a hash code for this Boolean object.
    Overrides: hashCode in class Object
    Returns: the integer 1231 if this object represents true; returns the integer 1237 if this
    object represents false.Unless I'm missunderstanding something ... If you were to have it implerment Comparable, you coud have two elements in a Set, one true and one false, with true always 1st and false always 2nd. No? If so, what's the point?
    ~Bill

  • Implements Comparable

    I am trying to create a holder object, which holds two values. It is called TwoTuple. I implemented Comparable so that I can use it in a Set.
    public class TwoTuple<A,B> implements  Comparable<TwoTuple>{
         public final String first;
         public final B second;
         public TwoTuple(String first, B b){
              this.first = first;
              second = b;
         public int compareTo(TwoTuple tt){
                     int result = first.compareTo(tt.first);
                     return result;
         public String toString(){
              return "Variable == " + first + "  Value == " + second;
    }This is my test class:
    public class Test{
         private static Set<TwoTuple> state = new HashSet<TwoTuple>();
         public static void main(String[] args){
              state.add(new TwoTuple<String,Boolean>("Testing", true));
              state.add(new TwoTuple<String,Boolean>("Testing", true));
              state.add(new TwoTuple<String,Boolean>("Testing", true));
              for(TwoTuple tt : state)
                   System.out.println(tt);
    }Output:
    Variable == Testing  Value == true
    Variable == Testing  Value == true
    Variable == Testing  Value == trueWhy am I still getting 3 of the same elements in this Set?

    This doesn't address the hash code issue, but here's an implementation of equals() for a similar class I have called Pair. It's generic & takes two objects F & S (first & second). Might apply to what you're doing, or may not.
    @Override public boolean equals(final Object object) {
         if (this == object) {
              return true;
         if (object == null) {
              return false;
         if (getClass() != object.getClass()) {
              return false;
         @SuppressWarnings("unchecked")
         final Pair<F,S> other = (Pair<F,S>)object;
         if (first == null) {
              if (other.first != null) {
                   return false;
         } else if (!first.equals(other.first)) {
              return false;
         if (second == null) {
              if (other.second != null) {
                   return false;
         } else if (!second.equals(other.second)) {
              return false;
         return true;
    }

  • Compile-time warning during javac of a Class that implements Comparable

    Hello All,
    I have defined a class as follows;
    public class CardTiles extends JButton implements Comparable{
    During normal compilation with javac, it tell me to use Xlint to compile and the warning it throws is below:
    CardTiles.java:4: warning: [serial] serializable class CardTiles has no definition of serialVersionUID
    public class CardTiles extends JButton implements Comparable{
    ^
    1 warning
    What does this warning mean?
    Many thanks!

    ejp wrote:
    you can choose to to differentiate between various versions of your CardTiles classThat's back to front. Serialization will always do that unless you stop it, which you can do via a fixed serialVersionUID. This tells Serialization that different versions of your class are compatible under serialization.I suppose I see it this way because I wouldn't have a serializable object without an ID. Without having an explicit ID the process isn't as transparent to me. It's the same sort of thing as using braces for statements when they're not necessary, e.g.
              if(check)
                   System.out.println("check is on");
              else
                   System.out.println("check is off");     versus     
              if(check) {
                   System.out.println("check is on");
              } else {
                   System.out.println("check is off");
              }

  • Trying to implement comparable interface

    I am writing a Book class, and in the class header I have stated the implements Comparable. I also have defined the public int compareTo( Book rhs). When I compile the Book class. I get the following message. The Book class needs to be abstract.
    I cannot create an object from an abstract class. What am I doing wrong?
    Ray

    You have maybe not implemented all methods in the interfaces you are using in your Book class. Are you using any other interface than Compnarable? Do you get any other error message?
    Anyway, this works when adding the Comparable interface, add this method to your Book class:
    public int compareTo(Object o) {
    return this.toString().compareTo(o.toString());
    And this method:
    public String toString() {
    return bookName; // Or anything that represents your book (for comparing)

  • MyInteger class- compile error - method doesnt implement comparable method

    I am trying to test how the code for a hash table works- I have 4 classes
    Hashable interface
    QuadraticProbableHashTable
    HashEntry
    MyInteger
    Everything is compiling but one error comes up saying that "Class must implement the inherited abstract method Comparable.compareTo(object)."
    I have a comparable method with the same signature as that in Comparable interface; in MyInteger.java where the problem is. However I still have the same problem.
         * Wrapper class for use with generic data structures.
         * Mimics Integer.
        public final class MyInteger implements Comparable, Hashable
             * Construct the MyInteger object with initial value 0.
            public MyInteger( )
                this( 0 );
             * Construct the MyInteger object.
             * @param x the initial value.
            public MyInteger( int x )
                value = x;
             * Gets the stored int value.
             * @return the stored value.
            public int intValue( )
                return value;
             * Implements the toString method.
             * @return the String representation.
            public String toString( )
                return Integer.toString( value );
             * Implements the compareTo method.
             * @param rhs the other MyInteger object.
             * @return 0 if two objects are equal;
             *     less than zero if this object is smaller;
             *     greater than zero if this object is larger.
             * @exception ClassCastException if rhs is not
             *     a MyInteger.
            public int compareTo( Comparable rhs )
                return value < ((MyInteger)rhs).value ? -1 :
                       value == ((MyInteger)rhs).value ? 0 : 1;
             * Implements the equals method.
             * @param rhs the second MyInteger.
             * @return true if the objects are equal, false otherwise.
             * @exception ClassCastException if rhs is not
             *     a MyInteger.
            public boolean equals( Object rhs )
                return rhs != null && value == ((MyInteger)rhs).value;
             * Implements the hash method.
             * @param tableSize the hash table size.
             * @return a number between 0 and tableSize-1.
            public int hash( int tableSize )
                if( value < 0 )
                    return -value % tableSize;
                else
                    return value % tableSize;
            private int value;
        }

    >
    You might want to also allow for cases where the
    value passed in is null, or the argument to the
    method is NOT a MyInteger object :-)
    Just a small note - the javadocs for Comparable#compareTo says the following:
    Throws:
    ClassCastException - if the specified object's type prevents it from being compared to this Object.
    So it's perfectly OK to blindly try to cast to the desired type in the sense that you are not violating the Comparable contract if the cast fails.

  • Implement Comparable with multiple arguments

    Is there a way of implementing Comparable<> with multiple different arguments to the Comparable generics?
    For example:
    public class Foo<K, V> implements Comparable<K>,
              Comparable<V>
    }The compiler complains with the error: "The interface Comparable cannot be implemented more than once with different arguments: Comparable<K> and Comparable<V>"
    Clearly, this cannot be done exactly like this, so I'm wondering if there is a different way of accomplishing the same functionality.
    Edited by: mgolowka on Apr 24, 2008 12:22 PM

    I'm working on creating a generic binary search tree. Currently I have this:
    public class BinarySearchTree<T extends Comparable<T>> implements Collection<T>
    }With the add() function, I can simply do add(T) that will use T's compareTo(T) method to find its place in the tree, however with the remove() and get() functions that I want to have would require an input of T, which isn't what I'm entirely looking for. I could change this to have a key/value pair so it's functionality is like a set, but I'm not sure if that's the best course of action. I could make it implement Map<K, V> to get that functionality...
    There is no time limit on this project as it is a part of a personal project.

  • Ok Why Does Boolean NOT implement Comparable

    Ok.. im looking for a logical reason to why Boolean does NOT implement Comparable?
    Every other wrapper does. ( Integer, Double ect.. ) Just not Boolean..
    anyone got any logical guesses as to Why?
    ( just for context here is how i came upon this.. )
    I have a quicksort algorythm that reads in an arraylist and does some manipulation of it. All that is demands is that the objects in the list be comparable. This algorythm has worked beautifully (and fast) for serveral months.. till someone put a Boolean in the list.. doh!
    Thanks,
    JMG

    Using the collections.sort() would mean that each object would have to implement comparable anyways. It also means that these objects would only be sortable by one set of tests. I wish to sort my objects by any of their properties. Hence now my properties must implement comparable. ( given that this app usings mostly int, double and String its not a big deal) What surprised me was the Double did not implement comparable where all other wrappers did.. thats it..
    mostly i was just currious as to if there was a larger reason to why it was not implemented other than we just could not decided which should be valued higher :)
    JMG

Maybe you are looking for

  • Sales Credit Memos, Payment terms and due date for payment

    Hello all, does anyone out there know how to get the terms of payment assigned to sales credit memos taken into account when the due date for payment is calculated in the accounting document?  (I know this is a bit puzzling as why should one need pay

  • ExtractValue and witespace

    Hello! I have an xml like this: <file>    <fieldend>'||chr(13)||chr(10)||'</fieldend> </file>and when i select it: select '"'||ExtractValue(XMLType('<file><fieldend>'||chr(13)||chr(10)||'</fieldend></file>'),                          'file/fieldend/t

  • IPC  for CRM 5.0

    Hi Experts, In CRM 4.0, to view analysis on Pricing tab we need to set parameter in COMM_IPC_URL table. UI_ANALYSIS --> http://<J2EE_server>:<port>/pricing In CRM 5.0 above setting is still valid?? from where can I get <J2EE_server>:<port> Thanks in

  • Incompatible video codec found in the preset

    Hello, First post so apologies if I am in the wrong section. I am trying to export a sequence from premier pro through the media encoder. for my project I am required to produce a 720p, 25fps h.264 .mov  however when selecting the format "Quicktime" 

  • Rearranging and duplicating pages in the thumbnails view?

    How do I rearrange and duplicate pages in the thumbnails view of pages? I could before, but can't with the new pages. DROPPING features?! That's not what an upgrade does! This hugely messes up my work!