If I have created a object array from a string array, how can I compare the items in the object array?
[ July 27, 2006: Message edited by: Angela Truce ]
public string sort();
public double sort();
public int sort()...etc
I want to be able to pass a string, double or an integer into one sorting algorigthm. Is this achieveable using objects?
3.2 345 34700 5.6 6.7 68
which is obviously wrong.
Does anyone know how I can start doing this?
Originally posted by Angela Truce:
I want to use my own sorting methods rather than the api's own sorts as the point of my program is to compare speeds of sorting algorithms. I just want to be able to compare more than just one type. So a string with another string, or a double with another double...etc. ...
Look at the way this is done in the standard API classes. Look at class java.util.Arrays, for example. It contains a whole range of sort(...) methods for different types.
Since Java 5.0 there's a better solution, fortunately: generics. Class Arrays contains this method:
public static <T> void sort(T a, Comparator<? super T> c)
which works on any type T. You just have to pass it a Comparator, which is the object that knows how to compare one instance of T to another instance of T.
If you've never seen generics, it can be a little difficult to understand them. You could call the above method on different kinds of arrays, for example:
Note that it is the same sort method that is used for strings as well as numbers above. The sort algorithm uses the Comparator object to compare two objects, and the sort algorithm itself doesn't need to care what kinds of objects it is sorting.
[ July 27, 2006: Message edited by: Jesper Young ]