aspose file tools
The moose likes Java in General and the fly likes Sorting an array of Number objects Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Sorting an array of Number objects" Watch "Sorting an array of Number objects" New topic
Author

Sorting an array of Number objects

David Duran
Ranch Hand

Joined: Feb 11, 2002
Posts: 122
Let's say I have a Number array filled with different kinds of Numbers

Number[] numArray = {new Integer(6), new Long(10), new Float(5.9), new Double(10.1)};

How would I go about sorting through such a list WITHOUT knowing what datatype the number actually is? The Number class doesn't support the compareTo() method.

In other words:



The line in question is the "***".

Is there an easy way to compare Number objects that are of different subclasses? Perhaps there isn't or it's simply escaping me-- it's been a long day. Remember, I don't want to assume that the first Number is an Integer, the next one is a Long, etc. The order and types of Numbers in numArray can't be assumed.
Greg T Robertson
Ranch Hand

Joined: Nov 18, 2003
Posts: 91
Take a look at the static method of java.util.Arrays named sort(Object o, Comparator c). Then take a look at the Comparator interface and implement your own NumberComparator class to do the comparison. This should work nicely.
Siripa Siangklom
Ranch Hand

Joined: Jan 26, 2004
Posts: 79


You can using method doubleValue() of Number class

if (a.doubleValue() > b.doubleValue()) {
...
somkiat puisungnoen
Ranch Hand

Joined: Jul 04, 2003
Posts: 1312
Originally posted by Greg T Robertson:
Take a look at the static method of java.util.Arrays named sort(Object o, Comparator c). Then take a look at the Comparator interface and implement your own NumberComparator class to do the comparison. This should work nicely.


Example : follow this solution

1. Comparator Class


2. How to use


This code will help you.


SCJA,SCJP,SCWCD,SCBCD,SCEA I
Java Developer, Thailand
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Sorting an array of Number objects
 
Similar Threads
invalid name patter error
Sun Cirtification
Java Generic Type on Class
AWT Event look for help
Simple J2SE 5.0 Tiger Notes