Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to sort an array of Strings 1

Status
Not open for further replies.

sparafucile17

Programmer
Apr 5, 2002
40
US
Does anyone know how to sort an Array of String without writing my own custom sorting method? I know in C++ that I could call the quicksort function and pass it my array an voila! it returned my array sorted. I tried looking it up on the sun site and I found something about the class "Arrays" where you could access the private member function sort() and pass it an array that way.

Can anyone give me some short sample code for this or any other easy sorting method?

Thanks,
Jeff Tackett
 
well since java.lang.String implements Comparable you can use both of these Array.sort members

public static void sort(Object[] a)

public static void sort(Object[] a,
int fromIndex,
int toIndex)

please note both methods are "public"

does that help?

-pete
 
Are you saying to invoke an "Array" class then? Or can I just do the following:

String myArray = new String[4];
myArray[0] = "A";
myArray[1] = "bunch";
myArray[2] = "of";
myArray[3] = "strings";

sort(myArray);

If this is true then I currently am not importing the right stuff. Could you right some example code for me? Just knowing what methods to use doesn't really help me that much.

Thanks,
Jeff
 
Ok,

To answer my own question, the anwser is this....

import java.util.Arrays;

//other stuff

String myArray = new String[4];
myArray[0] = "A";
myArray[1] = "bunch";
myArray[2] = "of";
myArray[3] = "strings";

Arrays.sort(myArray);

I just had to play around with it enough before I got it right. Maybe this will help someone else in the future :)

Regards,
Jeff
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top