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 Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Ignoring case while sorting an array

Status
Not open for further replies.

mluken

Programmer
Dec 31, 2003
54
US
I have an array that I need to sort alphabetically, however the following sort is case sensitive and I need to ignore case:

java.util.sort(myArray);

Any other suggestions?

Thanks!
 
I assume the array contains String objects. You can wrap each String object in another object that implements the Comparable interface, so you can ignore case:

Code:
class MyString implements Comparable
{
   public String s = null;

   public int compareTo( Object o )
   {
      return s.compareToIgnoreCase( ((MyString)o).s)
   }
}

When you sort the array of MyString objects, they will sort case-insensitive.
 
Most sort algoritums can take an optional comparator which is a class that has just the compareTo method (with 2 parameters). Which means that you don't need to wrap the strings to do the above -- cutting down on code. I'm not sure about the sort that takes an array, but most first class ordered containers will handle a comparator.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top