Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

arranging Strings in alphabetical order

 
Kevin Tysen
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20529
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Kevin Tysen
Ranch Hand
Posts: 255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic