Tuurbo46 said:
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.
--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation