| Author |
Can I sort String arrays?
|
Ananth Chellathurai
Ranch Hand
Joined: Nov 21, 2007
Posts: 347
|
|
Is there a way to sort a String array? I am using tree which gives a list of picked nodes through request ParameterValues. I am storing it to a String array. Can I sort these values? Ananth Chellathurai
|
Ananth Chellathurai [Walk on software]
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32638
|
|
|
Yes, it is easy since String implements the Comparable interface; you can use s1.compareTo(s2).
|
 |
Ananth Chellathurai
Ranch Hand
Joined: Nov 21, 2007
Posts: 347
|
|
So what should I compare to? I just want my string array to be sorted alphabetically. Ananth
|
 |
arulk pillai
Author
Ranch Hand
Joined: May 31, 2007
Posts: 3188
|
|
If you have special requirements
class test { public static void main(String[] args) { String words[] = { "Good", "Bad", "Ugly" }; Comparator<String> best = new Comparator<String>() { public int compare(String s1, String s2) { return s2.charAt(1) - s1.charAt(1} }; Arrays.sort(words); System.out.println(words[0]); System.out.println(words[1]); System.out.println(words[2]); } }
[ September 15, 2008: Message edited by: arulk pillai ]
|
Java Interview Questions and Answers Blog | Amazon.com profile | Java Interview Books
|
 |
Ananth Chellathurai
Ranch Hand
Joined: Nov 21, 2007
Posts: 347
|
|
Thanks a lot Arul. I will use this in my implementation. Ananth Chellathurai
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
You may want to use String.CASE_INSENSITIVE_ORDER if you want to sort it while ignoring the case.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Can I sort String arrays?
|
|
|