This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes arranging Strings in alphabetical order Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "arranging Strings in alphabetical order" Watch "arranging Strings in alphabetical order" New topic
Author

arranging Strings in alphabetical order

Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
I want to arrange some Strings in alphabetical order. Do I have to write a program that looks something like this:

String a;
String b;
if (a.charAt(0) > b.charAt(0)){

// more code here

}

Well, that is a very rough draft. What I mean is, do I have to write a method that compares all the chars of the Strings to each other, or is there some method in Java.Lang or Java.Util that does that?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19723
    
  20

String implements the Comparable interface, so you can use that to compare. Alternatively, it also has a compareToIgnoreCase method that allows you to compare regardless of the case:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Additionally you can use the sort methods, java.util.Collections.sort() and java.util.Arrays.sort(). These rely on having either a Comparable or a Comparator. String is already a Comparable, but if you want a different sort order you can make a Comparator instead.


"I'm not back." - Bill Harding, Twister
Kevin Tysen
Ranch Hand

Joined: Oct 12, 2005
Posts: 255
Thank you.
 
 
subject: arranging Strings in alphabetical order