The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
November 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Sorting a List

Posted by Matt Gerrans on November 07, 2001 at 12:48 AM

long is a primative type, not an Object, so you should instead do the comparison, for example:


class longs
{
public static void main( String[] args )
{
long x = 1;
for( long y = 0; y < 3; y++ )
System.out.println( x + " is " +
(compare(x,y)==0?"equal to":(compare(x,y)==1?"greater":"less")+" than") +
" " + y + "." );
}

static int compare( long x, long y )
{
return x < y ? -1 : x > y ? 1 : 0;
}
}

However, instead of all the gyrations you are doing, you could simply cast to directly to a Long object and use its compareTo() method: return ((Long)o1).compareTo((Long)o2);

Another thing, if you do want to get a long from a Long object (or an int from an Integer object, etc.), you don't need to do the toString() with parseLong(), you can (and should) use the longValue() method and get it directly.

- mfg


> public class LongComparator implements Comparator{
> public int compare(Object o1, Object o2) {
> long ss1 = Long.parseLong(o1.toString());
> long ss2 = Long.parseLong(o2.toString());
> return ss1.compareTo(ss2);
> }
> } //
> C:\jdk1.3.1_01\Greenhouse\GreenhouseControls.java:186: long cannot be dereferenced
> return ss1.compareTo(ss2);
> ^
> 1 error





Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us