Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2005

Tip: Looking for answers? Try searching our database.

Comparable interface

Thread view: 
Tuurbo46 - 25 Oct 2005 20:08 GMT
Hi

Im currently struggling to covert an existing base class to a comparable
interface - i cant find a web page with a good example.  Please could
somebody point me in the right direction?

Also, does anybody recommend a really good web site which covers the more
advanced concepts of java?

Thanks Turboo
klynn47@comcast.net - 25 Oct 2005 20:14 GMT
Well all you need to do is implement the Comparable interface which
involves giving an implementation to compareTo.
Tuurbo46 - 25 Oct 2005 20:23 GMT
yeah, i understand that part, but i need an example to work to! Sorry, im
quite new to java

Turboo

> Well all you need to do is implement the Comparable interface which
> involves giving an implementation to compareTo.
Oliver Wong - 25 Oct 2005 20:40 GMT
> yeah, i understand that part, but i need an example to work to! Sorry, im
> quite new to java
[quoted text clipped - 3 lines]
>> Well all you need to do is implement the Comparable interface which
>> involves giving an implementation to compareTo.

   Here's a short example (didn't verify this with a compiler, so might not
compile):

<code>
/**
* Represents an immutable integer.
*/
class MyInteger implements Comparable<MyInteger> {
 private int myValue;

 public MyInteger(int value) {
   this.myValue = value;
 }

 public int getValue() {
   return this.myValue;
 }

 /**
  * @throws NullPointerException if o is null.
  */
 public int compareTo(MyInteger o) {
   if (this.myValue < o.myValue) {
     return -1;
   }
   if (this.myValue == o.myValue) {
     return 0;
   }
   assert this.myValue > o.myValue;
   return 1;
 }
}
</code>

   Note that you might see code to implement compareTo like this:

<badCode>
 public int compareTo(MyInteger o) {
   return this.myValue - o.myValue;
 }
</badCode>

   Using subtraction like this introduces a subtle bug involving integer
overflow, so it's better to just use if statements like in the earlier
example.

   - Oliver
Roedy Green - 26 Oct 2005 05:14 GMT
><badCode>
>  public int compareTo(MyInteger o) {
>    return this.myValue - o.myValue;
>  }
></badCode>

Granted that code fails in the general case, but when writing
comparators, you often know for example that your ints are bounded in
a range nowhere near the sign bit, so the subtraction code is quite
safe.
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Oliver Wong - 25 Oct 2005 20:32 GMT
> Well all you need to do is implement the Comparable interface which
> involves giving an implementation to compareTo.

   If you implement the compareTo method, you should also override the
equals() and hashcode(). You must also ensure that the relation imposed by
the compareTo operation is a total ordering, which means you also have to
take into account where null appears in the order.

   - Oliver
Monique Y. Mudama - 25 Oct 2005 20:53 GMT
> Also, does anybody recommend a really good web site which covers the
> more advanced concepts of java?
>
> Thanks Turboo

I would recommend the book Thinking In Java, which is also available
for free online.

Signature

monique

Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Roedy Green - 26 Oct 2005 05:09 GMT
>Im currently struggling to covert an existing base class to a comparable
>interface - i cant find a web page with a good example.  Please could
>somebody point me in the right direction?

see http://mindprod.com/jgloss/Comparable.html

My own site tends to focus on beginning and intermediate users.

see http://mindprod.com/jgloss/jgloss.html

Try the Sun forums for more advanced discussion.

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Roedy Green - 26 Oct 2005 05:10 GMT
>Also, does anybody recommend a really good web site which covers the more
>advanced concepts of java?

You describe yourself as a newbie but want the advanced stuff??  How
about the intermediate?
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

Chris Smith - 26 Oct 2005 17:17 GMT
> Im currently struggling to covert an existing base class to a comparable
> interface - i cant find a web page with a good example.  Please could
> somebody point me in the right direction?

For most classes, which would just be ordered based on some set of
fields in order of significance, there is a simple pattern.

Before Java 5.0:

   public class A implements Comparable
   {
       private int a;
       private String b;
       private boolean c;

       public int compareTo(Object other)
       {
           A obj = (A) other;
           int result;

           result = new Integer(a).compareTo(new Integer(obj.a));
           if (result != 0) return result;

           result = b.compareTo(obj.b);
           if (result != 0) return result;

           result = c ? (obj.c ? 0 : 1) : (obj.c ? -1 : 0);
           if (result != 0) return result;

           return 0;
       }
   }

Java 5.0:

   public class A implements Comparable<A>
   {
       private int a;
       private String b;
       private boolean c;

       public int compareTo(A obj)
       {
           int result;

           result = a.compareTo(obj.a);
           if (result != 0) return result;

           result = b.compareTo(obj.b);
           if (result != 0) return result;

           result = c ? (obj.c ? 0 : 1) : (obj.c ? -1 : 0);
           if (result != 0) return result;

           return 0;
       }
   }

A few notes:

1. If the comparison is simpler -- such as when sorting based on only
one "key" field, where the other state is irrelevant for the natural
ordering -- then the code can be simplified.

2. If the ordering is more complex, you'll need to add to this form
somewhat.  For example, you might need to calculate intermediate values
for each object, and then compare those.

3. When comparing integer values, resist the temptation to just subtract
one from the other, unless you know that they are constrained to less
than half of the range of the resultant data type from that subtraction
(int or long).  There is a danger that an overflow will cause the wrong
value to be returned.

For the example above, if a = 2000000000, and
obj.a = -2000000000, then the quantity (a - obj.a) will actually be
negative due to overflow, and the code will fail.  That's why I used
Integer.compareTo instead of subtracting.

Floating point numbers (float and double) don't suffer from this
problem, but you should apply Math.signum to the result before casting
it to int, to avoid certain potential problems.

> Also, does anybody recommend a really good web site which covers the more
> advanced concepts of java?

For stuff like this, Josh Bloch's book is good.  (I don't know if it
specifically discusses this issue or not, but it addresses a lot of
stuff like this.)  I'm not aware of any web sites.

On the other hand, the term "advanced concepts of java" i9s somewhat
unclear, and I doubt many people would use it to describe implementing
Comparable.  Is there something different you had in mind.

Signature

www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.