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)

Similar Messages

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

  • Trying to implement 2 interfaces

    I am wondering how i might implement two different interfaces into a class (ItemListener and ActionListener) so that i can have checkboxes and buttons that will create events. The class already extends Applet so that i can't just extend an adapter and then implement one interface, i need to be able to inherit from Applet and each interface. Will i have to just create another class that implements one of them and create objects of that class?

    Hi,
    there's not problem to implement more than one interface:
    public class MyClass extends Applet implements ItemListener, ActionListenerRegards
    Ldinka

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

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

  • Using the Comparator Interface.Please Help.

    Hello there,
    I am trying out this example regarding the Comparator Interface.
    It works fine, but I havent really understood this at all.
    It deals with reverse sorting.
    import java.util.*;
    class MyComp implements Comparator {
    public int compareTo(Object a,Object b)
    String aStr,bStr;
    aStr = (String)a;
    bStr = (String)b;
    return bStr.compareTo(aStr)
    class MyComparator {
    public static void main(String[] args) {
    // Create a Tree Set
    TreeSet ts = new TreeSet(new MyComp());
    ts.add("C");
    ts.add("A");
    ts.add("P");
    ts.add("Z");
    ts.add("B");
    System.out.println(ts)
    Output : [Z, P, C, B, A]
    I have not understood the following at all:
    1) We are implementing the Comparator Interface in class MyComp.
    Now where is this being called in the MyComparator class?
    2) How is the reverse sorting taking place.?
    How is this comparing the different instances of the MyComparator class
    when I havent even instantiated the MyComparator class ?
    3) How is the interface method compare To(Object a,Object b) being invoked?
    Please can some please answer my questions.
    Regards

    class MyComp implements Comparator {
    public int compareTo(Object a,Object b)
    String aStr,bStr;
    aStr = (String)a;
    bStr = (String)b;Your reverse ordering is happening here.
    If you were to write
    return aStr.compareTo(bStr)
    the ordering would be in normal order.
    >
    return bStr.compareTo(aStr)The comparator that the treeSet uses is declared and instantiated here
    TreeSet ts = new TreeSet(new MyComp());
    1) We are implementing the Comparator Interface in
    class MyComp.
    Now where is this being called in the MyComparator
    or class? The comparator is being used by the TreeSet to order your entries
    >
    >
    2) How is the reverse sorting taking place.?Explained above. For further explaination look up comparator and String.compareTo()
    How is this comparing the different instances of
    of the MyComparator class
    when I havent even instantiated the MyComparator
    or class ?Also explained above
    3) How is the interface method compare To(Object
    a,Object b) being invoked?Internally by the TreeSet
    I hope this helped a little

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

  • Comparable interface selection sort

    Hi,
    I've created a Person Class with a comparable interface. And i've created an ArrayList People with varaibles from the person class in - First_name, Surname, Month(Birthday), Day(Birthday).
    Now i need to use selection sort to sort my arraylist into birthday order. In the Person Class i have a method which gives each person a different number for every possible birthday there is.
    I have created a selction sort but dont know how to call the birthday from my array list and then to sort it.
    This is my code for the selection sort so far:
    import java.util.ArrayList.*;
    public class Main
    public static void selectionSort(Comparable[] people)
    for (int k = people.length-1; k>0; k --)
    Comparable tmp;
    int Large = 0;
    for (int j=1; j<= k; j++)
    if (people[j].compareTo(people[k]) <0)
    Large = j;
    tmp = people[Large];
    people[Large] = people[k];
    people[k] = tmp;
    this method compiles but i need to sort the birthday and dont know how. Also i need to output the whole array in birthday order.
    Any help would be very greatful.
    Thanks
    Dave

    Hi,
    If my understanding is right..
    You are trying to sort with birthday as the primary sort criterria.
    For doing that, you have to write the comparison logic inside the compareTo() method implemented in the Person class (Inherited from Comparable Interface).
    i.e. The compareTo() method should use the the primary_sort_variable(here it is birthday or something derived from it) to return a boolean value for your need.

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

  • Comparable Interface

    I'm having trouble with my comparable interface...basically I just need to order a list by last name.... I'm getting a java.lang. class cast exception. I'm not sure why. I'll give some code but I have an Employee object with all the normal stuff name, salary etc. I throw those in a node and threw the node in an Object List. So here's my Object list method.../**
         * Inserts a node into its correct location within an ordered list
         * @param o - The element to be inserted into the list
        public void insert(Object o) {
            ListNode p = list;
            ListNode q = null;
            while (p != null && ((Comparable)o).compareTo(p.getInfo()) > 0) {
                q = p;
                p = p.getNext();
            if (q == null)
                addFirst(o);
            else
                insertAfter(q, o);
        }Here's my Employee class method: public int compareTo(Object o)
            Employee e = (Employee) o;
            return lastName.compareTo(e.getLastName());
        }My comparable class is normal...what you expect it to be and here's my call....
    public void orderList()
            ObjectList newList = new ObjectList();
            Iterator list = new Iterator(employeeObjectList);
            Employee e;
            while(list.hasNext())
                e = (Employee)list.query();
                newList.insert(e);
                list.next();
                   I might be doing this all wrong. I know eventually I will code it right but I'd like to have a better understanding of how the comparable interface works. If someone could give some thoughts I would appreciate it.

    while (p != null && ((Comparable)o).compareTo(p.getInfo()) > 0) {It looks like either the object you're trying to insert doesn't implement Comparable, or whatever is returned by p.getInfo() doesn't implement Comparable. If you know they're both Employees, then make sure the Employee class is actually declared to implement Comparable, and if you're using JDK 1.5 or later you might consider using generics to avoid some of the casts.
    public class Employee implements Comparable<Employee> {
        public int compareTo(Employee e) {
            return lastName.compareTo(e.getLastName());
    }

  • The Comparable interface

    Hi,
    i am writing a class that i would like to implement the interface Comparable. The java api says that the class must therefore have a method called "compareTo" which returns an int, for less than, equal to or greater than.
    My method does this, however the int it returns is actually meaningful as well, therefore the int that is returned is not just -1, 0 or 1 but other numbers... yet still corressponding to less than, equal to or greater than.
    Does this mean my class properly implements Comparable or does it HAVE to be -1, 0 or 1?
    Edited by: creman42 on Feb 3, 2008 10:30 PM

    creman42 wrote:
    no, but there was something about this sentence that i was slightly unsure about;
    "In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive. The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.) "They're saying that the return function of the sgn function will be -1, 0, or -1, and that by using such a function, you can determine the correctness of your compareTo method. Basically they're just being precise about how compareTo has to behave.
    My mistake for posting here, i should have posted in the New to Java board, this is obviously far too stupid a question, my sincere apologies It's not a stupid question but it's poorly asked. If the stuff about the sgn function was what confused you, then you should have mentioned it at the outset.

  • Comparable and comparator interface in java

    Hi All,
    How comparable and comparator interface works in java and when to use comparable and when to use comparator.please give me some example(code) as I am not able to understand the difference.
    Thanks
    Sumit
    Edited by: sumit7nov on May 17, 2009 4:45 AM

    Thanks,one more doubt.
    We have Collections.sort() method and we can sort any list by this method without implementing comparable or comparator interface.Then my question is when we need to implement comparable or comparator interface or when do we write our own compareTo() or compare() methods.
    Thanks
    Sumit

  • How to use the Comparable Interface?

    Now I have a question and I don't quite understand what the book explains. How does the comparable interface work? How can you redefine the equals implementation? How can you implement a compareTo? and how does this works with arrays? Thanks amigos......

    Not sure how to answer your question "how does the Comparable interface work" - what do you mean by "work"? It's purpose is to supply a known method that can be used to define an ordering on lists of objects. To do this you need to know how two objects compare to each other (less than, equal to, greater than) - and that's what the compareTo method gives you.
    You redefine the equals implementation by overriding the equals method - just declare a method in your class that has the same signature as equals and you're good.
    Your implementation of compareTo depends on your class. You just need to define how your classes compare to each other - for instance, assume you have an "Employee" class, that has an employee number and first name and last name fields. You want the natural ordering of lists of Employees to go in order by employee number. Define your compareTo method like:
    public int compareTo(Object o) {
        Employee emp = (Employee)o;
        if (emp.getEmployeeNumber() < this.getEmployeeNumber()) {
            return -1;
        else if (emp.getEmployeeNumber() == this.getEmployeeNumber()) {
            return 0;
        else {
            return 1;
    }You can sort arrays of things via the Arrays.sort method, which takes the array to sort and a Comparator (not Comparable) reference. The Comparator interface provides the same idea as the Comparable interface, but it's a stand-alone object that handles the comparison, as opposed to a method of some particular class. The compareTo method of the Comparator interface takes two Object references and returns how they compare.
    Good luck
    Lee

  • 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

  • Implementing Iterable interface

    Just trying to implement the the Iterable<> interface into my Stack class ... as far as I can tell I cannot specify a type beyond Object when iterating through it using the ForEach loop structure. Any thoughts on how to correct this or is my design limited?
    * @(#)Queue.java
    * @Matthew Cox
    * @version 1.00 2009/2/11
    import java.util.*;
    public class Stack<T> implements Iterable<T>
         private LinkedList<T> list;
         private int size;
        public Stack()
             list = new LinkedList<T>();
             size = 0;
        public void push(T node)
             if (node != null)
                  list.addFirst(node);
                  size++;
             else
                  System.out.println("Cannot push null value onto stack.");
        public T pop()
             T removedNode = null;
             if (!isEmpty())
                  removedNode = list.removeFirst();
             else
                  System.out.println("Stack is empty.");
             return(removedNode);
        public T[] toArray()
             return((T[]) list.toArray());
        public boolean isEmpty()
             return(size == 0);
        public boolean equals(LinkedList vList)
             return(list.equals(vList));
        public Iterator<T> iterator()
             return(list.iterator());
        public static void main(String[] args)
             Stack s1 = new Stack<Integer>();
             for (int count=0; count< 10; count++)
                  s1.push(new Integer(count)); //(int)(Math.random()*16+0)
             for(Object i : s1) //RIGHT HERE, I want to be able to say "Integer i : s1" but I get an incompatible types error
                  System.out.println(i);
    }I don't really understand why I would be getting the error stating the the type being sent back is Object ... my Iterator() method returns an iterator of type T not type Object from how I understood it... any thoughts?

    // Stack  s1 = new Stack<Integer>(); // this loses the type information
    Stack <Integer> s1 = new Stack<Integer>();

Maybe you are looking for