X
xarax
YUCK! Hugely inefficient instantiating 2 new Integer
instances, then immediately discarding them.
The Comparator approach is the best way.
Arithmetic with integers is subject to wrap-around without
any error or exception thrown. Thus, subtracting one point
from another point could yield the wrong algebraic sign.
Think about what happens if the first point is Integer.MIN_VALUE
and the second point is 1. Integer.MIN_VALUE-1 will wrap
(underflow) around to the Integer.MAX_VALUE.
The safest way is something like this:
public class ClubPointsComparator
implements Comparator
{
public int compare(final Object o1, final Object o2)
{
final Club c1 = (Club) o1;
final Club c2 = (Club) o2;
final int p1 = c1.points;
final int p2 = c2.points;
return ((p1 == p2) ? 0 : ((p1 < p2) ? -1 : 1));
}
}
Then instantiate a singleton instance of ClubPointsComparator
and use that for sorting the array of Club elements. The
implementation of Comparator above is far faster than
instantiating 2 new Integer instances for each array element
comparison.
If your Club class implements Comparable, then it
can only compare instances in one (natural) way.
Using Comparator instances lets you compare Club
instances in a variety of ways.
--
----------------------------
Jeffrey D. Smith
Farsight Systems Corporation
24 BURLINGTON DRIVE
LONGMONT, CO 80501-6906
http://www.farsight-systems.com
z/Debug debugs your Systems/C programs running on IBM z/OS for FREE!
instances, then immediately discarding them.
The Comparator approach is the best way.
Interesting, can you explain how your way is different? What is an
underflow problem?
Arithmetic with integers is subject to wrap-around without
any error or exception thrown. Thus, subtracting one point
from another point could yield the wrong algebraic sign.
Think about what happens if the first point is Integer.MIN_VALUE
and the second point is 1. Integer.MIN_VALUE-1 will wrap
(underflow) around to the Integer.MAX_VALUE.
The safest way is something like this:
public class ClubPointsComparator
implements Comparator
{
public int compare(final Object o1, final Object o2)
{
final Club c1 = (Club) o1;
final Club c2 = (Club) o2;
final int p1 = c1.points;
final int p2 = c2.points;
return ((p1 == p2) ? 0 : ((p1 < p2) ? -1 : 1));
}
}
Then instantiate a singleton instance of ClubPointsComparator
and use that for sorting the array of Club elements. The
implementation of Comparator above is far faster than
instantiating 2 new Integer instances for each array element
comparison.
If your Club class implements Comparable, then it
can only compare instances in one (natural) way.
Using Comparator instances lets you compare Club
instances in a variety of ways.
--
----------------------------
Jeffrey D. Smith
Farsight Systems Corporation
24 BURLINGTON DRIVE
LONGMONT, CO 80501-6906
http://www.farsight-systems.com
z/Debug debugs your Systems/C programs running on IBM z/OS for FREE!