Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Sort by absolute value (Math.abs)

807606Apr 20 2007 — edited Apr 20 2007
Hi,
I'm trying to find a way to sort an ArrayList by absolute value, similar to:
my @sortedArray= sort { abs $a <=> abs $b } @unsortedArray
in Perl

So, given an ArrayList of Integers: -7 -12 -3 5 8 9,
I want to sort them to be in the order of absolute value, namely -3 5 -7 8 9 -12

I've tried the following
public class Compare
{
    public ArrayList sortArray(ArrayList valuesToSort )
    {
        Collections.sort( valuesToSort, getComparator(  )  ) ;
        return  valuesToSort;
     }
    
    
    public static Comparator getComparator(  )
    {
        return new Comparator(  )
        {
            public int compare(Object o1, Object o2 )
            {
                return  Math.abs((Integer)o1).compareTo(Math.abs((Integer)o2));
            }
        } ;
    }
}

and then use it in some other code with
Collections.sort (valuesToSort, getComparator ( )); 
But it's not possible to use Math.abs on an Integer, and when I turn the o1 and o2 into ints, the error that I get is that I can't dereference int.

So, firstly, is there a short-cut to doing this, and secondly if there isn't, is there a good way of going about it

Many thanks,
Graham
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 18 2007
Added on Apr 20 2007
6 comments
950 views