Results 1 to 12 of 12
Like Tree3Likes
  • 3 Post By JosAH

Thread: again the Comparable interface

  1. #1
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default again the Comparable interface

    I'd like to post some questions concerning the next listed code.
    The code is from the Core Java book (the second volume).
    There are two classes: TreeSetTest and class Item which implements Comparable.
    The first class, which contains the main method is straight foreward and does not
    cause any problems for me.

    But the second class is kind of cryptic.
    1) who is calling the boolean equals(Object otherObject) method?
    2) and the hashCode() method?

    or are these methods overwritten in order to have a function
    at this specific class and Comparable interface?

    3) Here once again the compareTo method.
    The method gets its implementation and when it is called happens the following?

    the method call: return descrA.compareTo(descrB);

    public int compareTo(Item other)
    {
    return partNumber - other.partNumber;
    // which actually means here:
    // return descrA - descrB.descrA; // what ever that is?
    // or simply: return descrA - descrB;
    }
    mann this stuff is not easy for me!




    Java Code:
    /**
     *
     * 
     */
    /**
       @version 1.10 2004-08-02
       @author Cay Horstmann
    */
    
    import java.util.*;
    
    /**
       This program sorts a set of item by comparing
       their descriptions.
    */
    public class TreeSetTest
    {
       public static void main(String[] args)
       {
          SortedSet<Item> parts = new TreeSet<Item>();
          parts.add(new Item("Toaster", 1234));
          parts.add(new Item("Widget", 4562));
          parts.add(new Item("Modem", 9912));
          System.out.println(" the parts " + parts);
    
          SortedSet<Item> sortByDescription = new TreeSet<Item>(new
             Comparator<Item>()
             {
                public int compare(Item a, Item b)
                {
                   String descrA = a.getDescription();
                   String descrB = b.getDescription();
    
                   return descrA.compareTo(descrB);
                }
             });
    
          sortByDescription.addAll(parts);
          System.out.println(" the sorted parts " + sortByDescription);
       }
    }
    
    /**
       An item with a description and a part number.
    */
    class Item implements Comparable<Item>
    {
       /**
          Constructs an item.
          @param aDescription the item's description
          @param aPartNumber the item's part number
       */
       public Item(String aDescription, int aPartNumber)
       {
          description = aDescription;
          partNumber = aPartNumber;
       }
    
       /**
          Gets the description of this item.
          @return the description
       */
       public String getDescription()
       {
          return description;
       }
    
       public String toString()
       {
          return "[descripion=" + description
             + ", partNumber=" + partNumber + "]";
       }
    
       public boolean equals(Object otherObject)
       {
          if (this == otherObject) return true;
          if (otherObject == null) return false;
          if (getClass() != otherObject.getClass()) return false;
          Item other = (Item) otherObject;
          return description.equals(other.description)
             && partNumber == other.partNumber;
       }
    
       public int hashCode()
       {
          return 13 * description.hashCode() + 17 * partNumber;
       }
    
       public int compareTo(Item other)
       {
          return partNumber - other.partNumber;
       }
    
       private String description;
       private int partNumber;
    }

  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: again the Comparable interface

    1 & 2: They're public, so anything can call them. In this example, the Sets will call hashCode() and equals(...) on each element you add, to determine if it already contains that element.

    3: descrA.compareTo(descrB) returns descrA.partNumber - descrB.partNumber. The object you're calling it on is the 'this' and the argument passed to the method is the 'other'.
    Get in the habit of using standard Java naming conventions!

  3. #3
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: again the Comparable interface

    Thanks I have already figured that out as well.

  4. #4
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: again the Comparable interface

    It is obvious that when a class implements Comparable (in this case Comparable<Item>)
    several methods start to come in play like toString, hashCode(), compareTo() and equals().
    The above implementation of equals has a interesting format because within the method body of equals it again calls equals! One would think that that would case a undesirable loop?

    Java Code:
    public boolean equals(Object otherObject)              // * loop
       {
          if (this == otherObject) return true;
          if (otherObject == null) return false;
          if (getClass() != otherObject.getClass()) return false;
          Item other = (Item) otherObject;
          return description.equals(other.description)        //* loop
             && partNumber == other.partNumber;
       }

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,237
    Rep Power
    19

    Default Re: again the Comparable interface

    It doesn't call equals(...) on the same object.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  6. #6
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: again the Comparable interface

    db, how you know that?

  7. #7
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,018
    Rep Power
    6

    Default Re: again the Comparable interface

    Because its clearly visible in the code :s

    Java Code:
     if (this == otherObject) return true;

  8. #8
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,237
    Rep Power
    19

    Default Re: again the Comparable interface

    ... and the equals(...) in lines 7 and 8 are invoked on the values contained in the fields description and partNumber. Not on this and otherObject.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  9. #9
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: again the Comparable interface

    Wow this stuff is not easy for me, but it is key in understanding Java at the level I am at,
    so lets give it a try:
    -if (this == otherObject) return true; means in case the "otherObject" is "this"
    the code breaks of returning true, right?
    -So in case it is not "this" and jumping over the null option the code arrives at,
    line 5, and what the heck is going on there?
    The getClass() is like the instanceof, right?
    So if the two classes compared are different the code breaks off with a "false", right!
    -So in case they are the same we continuo reaching the equal which is not of "this" object, wow!
    As you said before, the equal fields that are compared by this (not "this") are of String fields of
    the declaration: private String description;
    SO THIS EQUAL IS IMPLEMENTED BY THE STRING CLASS, RIGHT?
    AND USES THE ALPHABETHIC ORDER, RIGHT?

  10. #10
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,525
    Blog Entries
    7
    Rep Power
    20

    Default Re: again the Comparable interface

    Yep, correct; think of a 'living' box (just use a bit of imagination); if I show that box another box and ask it whether or not they're equal, the box first checks if the other box is the box itself (there are no physical restrictions). If so, both boxes (the one and only box) are/is equal. If there is no other box (null) they're definitely not equal. If that other thing isn't a box, again, they're not equal. Otherwise both boxes need to be opened to check if the content is equal (the 'description' member variable).

    kind regards,

    Jos
    gimbal2, DarrylBurke and SurfMan like this.
    cenosillicaphobia: the fear for an empty beer glass

  11. #11
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: again the Comparable interface

    you know that song: "little boxes on the hill side", jos?
    malvina reynolds - little boxes - YouTube
    Last edited by willemjav; 07-09-2013 at 01:21 PM.

  12. #12
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,525
    Blog Entries
    7
    Rep Power
    20

    Default Re: again the Comparable interface

    Quote Originally Posted by willemjav View Post
    you know that song: "little boxes on the hill side", jos?
    malvina reynolds - little boxes - YouTube
    Now I do ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Comparable vs. Comparator interface?
    By Armin Beganovic in forum New To Java
    Replies: 1
    Last Post: 07-30-2012, 11:41 AM
  2. Comparable interface
    By diamonddragon in forum New To Java
    Replies: 17
    Last Post: 02-01-2012, 12:07 AM
  3. Implement Comparable interface
    By JojoDiaz in forum New To Java
    Replies: 3
    Last Post: 11-07-2011, 07:10 AM
  4. Comparable Interface
    By Yelrubk in forum New To Java
    Replies: 3
    Last Post: 04-28-2010, 02:46 PM
  5. interface Comparable<T> problem
    By Lennon-Guru in forum New To Java
    Replies: 3
    Last Post: 03-05-2008, 12:17 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •