Connecting Tech Pros Worldwide Forums | Help | Site Map

Sorting a String array

Newbie
 
Join Date: Feb 2008
Posts: 1
#1: Feb 27 '08
Hi,

I'm reading in a delimeted text file (X rows, 4 columns) in this case tab delimited. I would like the array to be sorted in the array.

This is the best I have come up with, but it seems very harsh. Is there no easier way of sorting an array?

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. String[][] tempData;
  4. tempData = new String[20][4];
  5.  
  6. [ stuff deleted when using CSV to read in the file ]
  7.  
  8. Arrays.sort(tempData, new Comparator<Object>() {
  9.     public int compare(Object o1, Object o2)
  10.     {
  11.     try
  12.     {
  13.         String[] s1 = (String[]) o1;
  14.         String[] s2 = (String[]) o2;
  15.         if ((s1[0] == null) || (s2[0] == null))
  16.         {
  17.             return 0;
  18.         }
  19.         return s1[0].compareTo(s2[0]);
  20.     }
  21.     catch (ParseException e)
  22.     {
  23.         e.printStackTrace();
  24.         return Integer.MIN_VALUE;
  25.     }
  26. }
  27.  
The null check is because although I have a 20x4 String array defined, there is no gurantee that there will be exactly 20 rows, there might be less.

Thanks.

BigDaddyLH's Avatar
Moderator
 
Join Date: Dec 2007
Location: Kelowna, BC Canada
Posts: 1,212
#2: Feb 27 '08

re: Sorting a String array


I would use a List<SomeClass>, not a String[20][4], where SomeClass is Comparable.
Reply