• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Sorting an array of Number objects

 
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


You can using method doubleValue() of Number class

if (a.doubleValue() > b.doubleValue()) {
...
 
Ranch Hand
Posts: 1312
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic