You will use the same Arrays.sort() method passing in your multi-dimensional array and a second Comparator parameter which specifies your ordering requirements. For example:
import java.util.*;
public class MultiSort
{
public static void main(String args[])
{
String[][] names = {
{"Smith","John"},
{"Smith","Albert"},
{"Jones","Sonny"},
{"Jones","Sam"},
};
System.out.println("Before sort...");
printArray(names);
System.out.println();
Arrays.sort(names,new LastFirstComparator());
System.out.println("After sort...");
printArray(names);
}
public static void printArray(String[][] array)
{
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
System.out.print(array[i][j]);
System.out.print("\t");
}
System.out.println();
}
}
}
class LastFirstComparator implements Comparator
{
public int compare(Object obj1, Object obj2)
{
int result = 0;
String[] str1 = (String[]) obj1;
String[] str2 = (String[]) obj2;
/* Sort on first element of each array (last name) */
if ((result = str1[0].compareTo(str2[0])) == 0)
{
/* If same last name, sort on second element (first name) */
result = str1[1].compareTo(str2[1]);
}
return result;
}
}
> i know sorting an array is by java.util.Arrays.sort(
> ) method, but how can i sort a multidimensional
> array. for example an array containing two columns
> lastname and firstname.
You could consider a different data structure. Why not have a Person class for example and store the objects in say an ArrayList. You still will need to supply a Comparator object to the sort method but maybe it's a little more straightforward.
I copied and tried to compile this example and am getting an error I don't understand. I'm pretty new to Java programming; any help would be appreciated.
The error is:
MultiSort.java:20: warning: [unchecked] unchecked conversion
found: LastFirstComparator
required: java.util.Comparator<? super java.lang.String[]>
Arrays.sort(names,new LastFirstComparator());
^
MultiSort.java:20: warning: [unchecked] unchecked method invocation: <T>sort(T[]
,java.util.Comparator<? super T>) in java.util.Arrays is applied to (java.lang.S
tring[][],LastFirstComparator)
Arrays.sort(names,new LastFirstComparator());