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.

Similar Messages

  • 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

  • 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

  • Stuck using the Comparable Interface

    I am having problems implementing the Comparable Interface in my class. I have written the compareTo method but this is not working. Can anyone see what I am doing wrong in the coding of this method. Thanks !!. (see below code for the class :
    package tma02q1;
    import java.util.*;
    This is the outline of the basic Video class.
    Such a class describes the videos stocked by a branch of a video hire company
    As well as completing the given methods you will need to make further additions
    to this class.For further details you should study the BranchTest class.
    public class Video implements Comparable {
    // declare two instance variables
    // a String to hold the video title
    // an int to hold the video rental cost - cost is held in pence
    private String aTitle;
    private int aCost;
    public Video(String aTitle, int aCost) {
    this.aTitle = aTitle;
    this.aCost = aCost;
    private void setTitle(String aTitle) {
    this.aTitle = aTitle;
    public String getTitle() {
    return aTitle;
    private void setRentalCost(int aCost) {
    this.aCost = aCost;
    public int getRentalCost() {
    return aCost;
    public String toString() {
    return "Video Title = " + aTitle + " which has a rental cost of = " + aCost;
    public boolean equals(Object vid) {
    Video arg = (Video) vid;
    return (this.aTitle.equals(arg.aTitle)
    &&this.aCost==arg.aCost);
    public int compareTo(Object vido) {
    Video arg = (Video) vido;
    int comp = aCost.compareTo(arg.aCost);
    return comp;

    You've got another serious problem with your code. Both the equals and compareTo methods will throw a ClassCastException if the parameter is not a reference to a video object. Using the instanceof operator will however solve the problem. E.g.
    public boolean equals(Object o) {
      if (o instanceof Video) {
        Video  arg = (Video) o;
        return (this.aTitle.equals(arg.aTitle)
                &&this.aCost == arg.aCost);
      else
        return false;  
    }The same approach is applicable to the compareTo method.
    Regards

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

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

  • Sort column by without case sensitive  using Comparator interface

    Hello,
    When i sorted my values of a column in a table it was showing all sorted upper case letters at top rows and all sorted lower case letters on bottom. So i would like to sort values without case sensitive order. Like. A, a, B, b, C, c....
    I am using Collection class to sort vector that contains the values of a column as an object and using Comparator interface to sort the values of a column in either ascending and descending order. It facilitates to compare two objects like.
    <class> Collections.sort(<Vector contains values of column to be sort>, <Comparator interface>);
    and in interface it compares two objects ((Comparable) object).compareTo(object);
    Now Let's suppose i have three values say Z, A, a to sort then this interface sorted in ascending order like A, Z, a
    but the accepted was A, a, Z. So how can i get this sequence. I would like to sort the values of a column without case sensitive manner.
    Thanks
    Ashish Pancholi
    Edited by: A.Pancholi on Dec 29, 2008 1:36 PM

    [http://java.sun.com/javase/6/docs/api/java/lang/String.html#CASE_INSENSITIVE_ORDER]

  • Will the apple tv 2 receive a software update for the new interface?

    Will the apple tv 2 receive a software update for the new interface?

    J.T.Holloway wrote:
    I don't love it, but I don't dislike it either.  Between the two, at least initially, I think I prefer the previous interface.
    I know that will be the case for me.
    J.T.Holloway wrote:
    The new one is a little more Apple-like with icons instead of lists, but I liked having everything right on the screen before and now I have to scroll down to get to the icons below the tv screen view.
    The old interface wasn't perfect but logical - as you say the icons are for the iPhone and iPad crowd, and as i see it will entail more scrolling and button hopping on the remote.
    J.T.Holloway wrote:
    I do like the icon look as it is more like the iPad, iPhone, Dashboard, etc.
    Quelle surprise......
    It's a bit like the redesign of these discussion fora - the new layouts are designed for the younger generation but far too much scrolling and hard work to find what you want compared to the old format.
    I HATE SCROLLINGTO FIND THINGS
    Sorry, rant over.

  • 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

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

  • Why oh why was it fixed when it wasn't broken..the user interface

    This is a serious error on Apples part to alter the way this critical program operates
    its like taking away critical controls from an automobile...like the steering wheel
    Its that bad its at the level like Microsoft would have done.
    It may operate with all the same features...but where are they...not on the iTunes desktop
    where one could surf iTunes to look at, get, explore
    big mistake & an even bigger one not to listen to customers...
    Bruce L. Farrar

    Steve
    Sorry I just cant see how you can compare iTunes 10.7 &  iTunes 11 - yuo are in the minority  !!
    Everyone I speak to has the same view on this:
    That 11 hasnt the same user interface & controlability.For me this is fundamental in the way I used iTunes to "surf" what was available from what I already had.I find the way I have to go through things in a list poor to unusable. OK Apple may want to have the same interface accrooss the whole product platform - but why the capability of a Mac with a omplete keyboard & larger screen allows for more possibilities than say an iPhone which I reackong any user will realise & accept...basically the iTunes on mac platform has been dumbed down & is now far less capable
    The search "engine" that hasnt got fields to select to narrow down or focus a search is just riduculous & it doesnt work that well as whats comes back has to be searched through again.
    Using iTunes 10.7 & before was an "adventure" into music or material you knew & you found things you didnt know about & to do this was easy & enjoyable. Ifound previosly I could find a single track out there quickly & also explore.
    Whats happened is fundamentally bad - lets give a comparison - say if the whole user interface of the MacOS or write was altered, made significantly different...everyday tasks that you could do before had to be re learnt or just couldnt be done.
    Even Microsoft are carefull about making changes to the way things work & the way that a user interfaces with this...one carefull step at a time OK Microsoft "things" have to recieve this type of carefull scrutiny & adjustment - but Microsoft onthe whole take thier customers with them. Learning point that Apple have yet to realise & learn from
    Previous to this from Lion to Mountain Lion there was Frontrow a simple little program that gave a feature that me for one used (& enjoyed) regularly.....on the Mac doing something important...take a break, relax & enjoy some music...one press of the remote & you had all you music & videos there to be used...like a big iPod...really ver good. Finished relaxing or taking a break get back to work just where you left off, an impressive feature that was taken awy & replaced with NOTHING.
    So for me at least the usability & functionallity of the Apple experience has deteriorated...for no appreciable gain....for just a commonality of controls accross the products.
    Its called "change for changes sake" & in this case the customers werent consulted they were totally ignored in being left with something that is retrograde.
    The very fact that I am here with others making comment is proof postive that the situation is a definate backwards step. I just hope that for Apple its a "blip" i.e. an error that will realised & corrected...
    I have been using Apple products from 1989...I am not a Microsoft refugeee or reluctant convert who is throwing mud..just the opposite in my family we have:
    4 Macbook Pros,
    an iMac,
    4 iPods,
    4 iPhones
    Apple TV
    all backed up ona time capsule.
    We have lived through the bad times & good...I realise that Steve Jobs cant come back...but I am sure he would have listed & then gone back to the teams & forced the change backs through.

  • Why don't we  want to define equals() in Comparator interface...........

    Comparator interface has two methods: compare() & equals(). If we implement Comparator in our class(not abstract) itz unnecessary to define equals(). Why? (If we implement an interface we should define all its methods inside the class where we implement it)....

    It all hinges on what the type of Object is. Is it
    of type Comparator or the parameter you expect to be
    passed to compareTo?
    I say that Comparator makes the most sense to me.
    If you read Joshua Bloch's stuff about Comparable, he
    says it's very important to make sure that compareTo
    obeys the same contract as equals for that object.
    Why would you want to try overriding the behavior
    that might already exist in the Object that's the
    parameter for compareTo? That would be bad design,
    IMO. You might change the intentions of the person
    who wrote that class.
    %the docs say it's for comparing Comparators.
    from the docs:
    Additionally, this method can return true only if the specified Object is also a comparator and it imposes the same ordering as this comparator
    I read that to mean that the compared objects should both be Comparators (obviously) and both result in the same ordering. seems to me the method is declared on this interface to draw attention to this addition to the contract, as much as anything else

  • Editing JPEGs with the RAW interface

    I discovered a way to edit JPEG images using the RAW interface. I go to File > Open As... instead of File Open.., change the format in the lower window to "Camera RAW" and click open.
    I am fully aware of the benefits of shooting in RAW as compared to JPEG and I'm not approaching this with the expectation that I'll get better results editing JPEGs using this approach. What I am addressing is the fact that the tools in the RAW interface are more consolidated and faster to use then going through a typical workflow using Levels - Hue/Saturation - Shadows/Highlights etc.
    The other benefit seems to me is you can use the same RAW controls numerous times while editing, while you're only suppost to use Levels Hue/Saturation controls once so as to minimize the impact these tools have on image degradation.
    Am I on to something here or out in left field?
    Opinions please...
    Deep Woods

    Does two minor changes not equal one major change? I'm not sure. This also begs the question... at what point in using Levels, contrast or saturation tools does editing change from minor to major? Maybe I'm splitting hairs, but I don't believe everyone out there would agree at what point this is defined.
    True, major and minor is subjective, but I can see how you adjust the black point in levels, and then you come back into the photo later and decide to slide it a little more, I don't have any particular qualms about doing this, and I don't think anyone can look at the resulting image and say -- see, right there, quality degradation because you used levels twice.
    The place where levels is most dangerous is when you either do ridiculous things, like move the sliders almost all the way to the middle, and then move them back almost all the way to the edges; or when you are getting posterization (which can happen from even a single use of levels).
    Many publications I came across over the years indicate single adjustments only when using these tools on JPEGs, unless of course one is using Adjustment Layers.
    Never read that. Can you please provide a reference?
    This is why I was hoping for lots of feedback like yours on the issue of using the RAW interface to edit JPEGs. I've received very little feedback on this issue which tells me it is a little known option to users of Photoshop. It is so much easier to edit a JPEG using the RAW interface, rather than go through the conventional workflow with the other tools in Photoshop. So far no one has given me reason to think otherwise.
    Yes, I agree editing JPGs in the raw interface has a number of advantages, ease of use being one of them. Non-destructive editing is another advantage. My guess as to why so few people use this tool is that: 1) PSE is a very overwhelming program, and once you learn the traditional way to do things (which is what you get from most books and tutorials), you don't want to bother learning another way to edit your photos; and 2) RAW scares many people.

  • The new interface

    Hi, recently the user interface on the satnav app changed, instead of the numbers being on the left they are now spread accross the bottom of the phone.  Is the anyway to roll back to the old version of the app and will the be an option in future to toggle left/bottom for the numbers as I am very unhappy with this.
    I know it may seem to some like a silly thing to get annoyed about but satnav and camera are the two main features I desire in a phone (as they call all call/email/text great these days) and I bought the 920 on launch as it was great in all these areas, if the satnav app had looked like this at launch I would have bought another phone, its a simple case of having to take your eyes off the road for longer to scan them (and mount the satnav higher) and the new interface basically sacrifices functionality for looking prettier

    ray sharpe wrote:
    Have any of you noticed the new playlist icons and album art displays? What else have you seen thats new?
    Yes, I agree they're nice in an informational sense, but the downside is a continuing creep to a very cluttered interface compared to software 1.0/1.1.
    My better half will have no idea what half the icons mean as she doesn't touch iTunes to compile playlists herself.
    AC

  • Comparable and Comparator Interface - Collections

    Hi All
    Please let me know when to use Comparable interface and Comparator interface. ?
    Any sort of information is highly appreciable .
    Matt

    Matt wrote:
    @ jverd      
    So, when you googled, and found tutorials, and worked through those tutorials, and read the javadocs for those classes, what in particular did you not understand?If everything would work like that what will be the use of forums like this , It does work like that, for people who aren't lazy. The use of these forums, as indicated by my first reply, is among other things, when you've done your own research, as you should do, and run into something you don't understand.
    so dont try to be smart :(Maybe you should try to be smarter.
    Lets try not to abuse the forum with exchanges like this. The only abuse so far has been you expecting the forum to be a substitute for doing your own research.
    I know how to use Comparable and Comparator but dont know when to use these in a real time application.That statement says nothing about your problem. The only information it carries is that you don't know what the term "real time" means.

Maybe you are looking for

  • Opening multiple images in Photoshop CS3 windows

    I can open an image just fine in Photoshop CS3 by going file-open and clicking on the file, I then want to bring in another image into Photoshop CS3 by using file-open which I can do but then the first image disappears and only the second image is in

  • Non-XML payload in graphical mapping

    Experts, I have a scenario where I need to trigger a graphical map which eventually populates an IDoc (custom) structure but the Idoc is not being populated with any of the source field. My source data is a flat file. 1. I dont want the src file cont

  • Problems with spacing in table(cs2, PC)

    Hi everyone I have imported a excell file into indesign cs2 (using place). When I mark the whole table I cannot change the height of the rows. I can choose at least or exactly however I cannot change the size, that box I gray. What am I doing wrong?

  • Tab Navigator Problem

    Hi,     I have a tab navigator in which i have loaded five canvas. I want the canvas to be loaded after clicking the confirm box.Please give me a code for this. Reagrds, Jayagopal P.S

  • VI Conversion from LV5 -- LV2009 (or LV8.5)

    Hello, could someone please convert the VI so that I can open it with LV 2009 (of LV8.5)? Thank you very much! Solved! Go to Solution. Attachments: MonoMove.vi ‏65 KB