Quick Java Questoin

AgaBoogaBoo

Lifer
Feb 16, 2003
26,108
5
81
public abstract int compareTo(Object obj);

would that return a boolean saying if they're the same or not?
 

pkananen

Senior member
Mar 13, 2003
644
0
0
no, it will return an int (0 and 1 = false and true in C++ is not the same in Java, where boolean is a seperate primitive type not interchangeable with ints 0 and 1).

BUT, its an abstract function - it can't actually be used. You can create a child class where compareTo will be implemented.
 

AFB

Lifer
Jan 10, 2004
10,718
3
0
Originally posted by: pkananen
no, it will return an int (0 and 1 = false and true in C++ is not the same in Java, where boolean is a seperate primitive type not interchangeable with ints 0 and 1).

BUT, its an abstract function - it can't actually be used. You can create a child class where compareTo will be implemented.

It returns 0 if it is equal, 1 if the object you are calling it on (the one who the method belongs to, not the one you're passing), or -1 if it is less. Going with this, it shouldn't be too hard to work out some sorting algorithms in your head.

I'll use Integer obejcts for this example as they are the best thing suited for explination.
 

kamper

Diamond Member
Mar 18, 2003
5,513
0
0
Technically it doesn't have to be 1 or -1, just >0 or <0 ;)

Integer.compareTo(Integer) happens to always return -1 or 1, though. I don't understand why they didn't just return (thisVal - anotherVal).
 

AFB

Lifer
Jan 10, 2004
10,718
3
0
Originally posted by: kamper
Technically it doesn't have to be 1 or -1, just >0 or <0 ;)

Integer.compareTo(Integer) happens to always return -1 or 1, though. I don't understand why they didn't just return (thisVal - anotherVal).

True, but it seems to be a de facto custom to just return -1 or 1. However, you should be prepared when others don't do this.