This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
If you are referring sorting a String array, you could use Arrays.sort(obj);
Joined: Nov 30, 2005
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. The only way I can see is to write individual methods for each primitive type which would not be ideal as the code will be very long. ie. 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?
sure you can pass in raw Objects, but then you'd have to do all the type checking inside the methods. Maybe what you really want is an untyped language like Python or Ruby, and sink with the Titanic as soon as an incorrect type appears.
Joined: Nov 30, 2005
ok, I have an idea. If I sort using strings (as its the easiest) then I could write my own sort for numeric values as when I sort doubles/ints a strings it would sort them like this:
3.2 345 34700 5.6 6.7 68
which is obviously wrong. Does anyone know how I can start doing this? thanks.
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 ]