Sorting a String array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aram535
    New Member
    • Feb 2008
    • 1

    Sorting a String array

    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?

    Code:
     
    
    String[][] tempData;
    tempData = new String[20][4];
    
    [ stuff deleted when using CSV to read in the file ]
    
    Arrays.sort(tempData, new Comparator<Object>() {
        public int compare(Object o1, Object o2)
        {
    	try
    	{
    		String[] s1 = (String[]) o1;
    		String[] s2 = (String[]) o2;
    		if ((s1[0] == null) || (s2[0] == null))
    		{
    			return 0;
    		}
    		return s1[0].compareTo(s2[0]);
    	}
    	catch (ParseException e)
    	{
    		e.printStackTrace();
    		return Integer.MIN_VALUE;
    	}
    }
    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
    Recognized Expert Top Contributor
    • Dec 2007
    • 1216

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

    Comment

    Working...