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;
}

Similar Messages

  • 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

  • Abstract Class that implements Comparable

    I am trying to understand how a comparable interface works with an abstract class. Any help is greatly appreciated.
    I have a class ClassA defined as follows:
    public abstract class ClassA implements Comparable I have a method, compareTo(..), within ClassA as follows:
    public int compareTo(Object o) I have a sub-class ClassB defined as follows:
    public class ClassB extends ClassAI am receiving a compile error:
    Class must implement the inherited abstract method packagename.ClassA.compareTo(Object)
    Should or can the compareTo be abstract in ClassA and executed in ClassB? Just not sure how this works.

    ???? if you are inheriting from an abstract class your subclass must implement methods that were declared in the parent (abstract) class but not implemented
    When in doubt, refer to the Java Language Specification..

  • 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)

  • Implementing Comparable interface? Help please.

    Why am I getting the following error?
    Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to chapter10.RectangleJust look at the test class and ComparableRectangle class if you can find the bug.
    Here are the 3 of 4 classes:
    package chapter10;
    public class TestComparableRectangle {
        public static void main (String[] args) {
            ComparableRectangle area1 = new ComparableRectangle(3.0, 6.0);
            ComparableRectangle area2 = new ComparableRectangle(5.0, 4.0);
            int result = area1.compareTo(area2.getArea());
            if (result == -1)
                System.out.println("area1 " + area1.getArea() + " < "
                        + area2.getArea() + " area2.");
            else if (result == 0)
                System.out.println("area1 " + area1.getArea() + " = "
                        + area2.getArea() + " area2.");
            else
                System.out.println("area1 " + area1.getArea() + " > "
                        + area2.getArea() + " area2.");
    package chapter10;
    public class ComparableRectangle extends Rectangle implements Comparable{
        /** Construct a ComprableRectangle with specified properties */
        public ComparableRectangle(double width, double height) {
            super(width, height);
        /*  Implement the compareTo method defined in Comparable */
        @Override
        public int compareTo(Object x) {
            if (getArea() > ((Rectangle)x).getArea())
                return 1;
            else if (getArea() < ((Rectangle)x).getArea())
                return -1;
            else
                return 0;
    package chapter10;
    public class Rectangle extends GeometricObject {
        private double width;
        private double height;
        public Rectangle(){
        public Rectangle (double width, double height) {
            this.width = width;
            this.height = height;
        // Return width
        public double getWidth () {
            return width;
        // Set a new width
        public void setWidth (double width) {
            this.width = width;
        // Return height
        public double getHeight () {
            return height;
        public void setHeight (double height) {
            this.height = height;
        // Return area
        public double getArea () {
            return width * height;
        //Return parimeter
        public double getPerimeter() {
            return 2 * (width + height);
    }Thanks in advance.

    Thanks a lot friend. It has been a week I've been trying to find the problem. In fact I was adding/casting the left side, but never tried the right side.
    This is what I changed it and it worked.
    int result = area1.compareTo(area2);Thank you.

  • Serialize a value object that implements Comparator T

    Hi.
    I'm implementing a VO like this:
    public class RegionVO implements Serializable, Comparable<RegionVO>My problem is that i need that the class could be serialized completely.
    The VO will be transfered throught EJB's and by past experiences with EJB 2 projects (the actual project is developed with EJB 3) and running the project in clusters, the application crashes to use VO defined like that.
    I think that the problem is caused by implement Comparable too, this inteface isn't serializable and even if implement of Serializable interface, at least 1 method (compareTo(RegionVO o))not would serializable.
    My question is if that is true, how to solve to serialize the entire VO.
    Thanks.
    Edited by: terinlagos on Jul 24, 2008 2:48 PM

    terinlagos wrote:
    Well, the question was because if eventually could have the same problem when in the future the application run in a clusterized server. Actually in my pc has no problem.Well at least you are thinking that clustering will introduce problems you don't have currently.
    I suggest you start trying to cluster you application as early as possible, you undoubtedly will have allot of lessons to learn (I have never seen a cluster solution from an it-works-on-my-pc solution not run into unexpected problems)
    Note: you can run a "clustered" solution on a single PC just in multiple JVMs (which would be deployed to different machines in your final solution)
    You should make looking at this your top priority. IMHO.

  • 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!

  • 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 error

    Hi,
    I've got code like that:
    import java.lang.Comparable;
    import java.util.*;
    * @author Adam
    public class Person implements Comparable { //this line causes error
        /** Creates a new instance of Person */
        public Person() {
        }I've got also another class DataBase, where I have ArrayList of Person, I would like to sort them by surname, in clas person I have also methods like that:
            public boolean equals(Object o)
            if (!(o instanceof Person))
                return false;
            Person n = (Person)o;
            return n.surname.equals(surname);
            public int compareTo(Person n)
             int lastCmp = surname.compareTo(n.surname);
             return (lastCmp != 0 ? lastCmp :
                    surname.compareTo(n.surname));
              public int hashCode()
               return 31*surname.hashCode();
              }My Error is: Person is not abstract and does not override abstract method compareTo(java.lang.Object) in java.lang.Comparable
    But class Person shouldn't be abstract, te line which causes the error is: public class Person implements Comparable, I don't know why. Can enyone help me?

    So I'll try to create abstract class with different
    name.
    But here->http://www.onjava.com/lpt/a/3286 they don't
    have any problems with implementing this.
    Message was edited by:
    snakeomwhy do you think you want an abstract class??
    you've got a perfectly good tutorial right there, that tells you exactly what you need to do. just follow that. read your code again and see if there's anything in your first class that does any comparing (clue: there isn't)

  • 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");
              }

  • 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 { ... }

  • 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

  • How do I open two profiles at the same time?

    until i updated to Firefox 7 i got prompted to which profile i want to open every time i open firefox, i am using one profile to play and one for work. i get prompted the first time but not the rest of the time how do i fix it so that i can again run

  • What are the best solutions for data warehouse configuration in 10gR2

    I need help on solutions to be provided to my Client for upgrading the data warehouse. Current Configuration: Oracle database 9.2.0.8. This database contains the data warehouse and one more data mart on the same host.Sizes are respectively 6 Terabyte

  • Not allowing the wifi to be turned on on iPhone 6

    Wifi signal goes down to one bar and when I go to the general button nothing shows up and I have to do a force shut down

  • Re: Query for Cost Code in oracle HRMS

    Hi I am also looking out for something similar. I need the query which will give me the costing details of each of the elements (Costed Element Name | Costing Account | Balancing Account). Any pointers on this would be highly appreciated. Thanks Rega

  • SQL Query: How to pass list of values to the IN operator

    Hi, I'm trying to pass a list of values to the WHERE <a> IN <list> I dont want to use dynamic cursors (REF CURSOR). Is this possible using Oracle SQL? Please let me know. My program: DECLARE list_of_ids := '10, 20, 30'; SELECT MAX(sal) INTO max_sal F