• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorting an array of Number objects  RSS feed

 
David Duran
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


You can using method doubleValue() of Number class

if (a.doubleValue() > b.doubleValue()) {
...
 
somkiat puisungnoen
Ranch Hand
Posts: 1312
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!