0

I need to sort the following array:

String [][] myArray = {{"John", "3", "10"}, {"Paul", "16","2"}, 
                       {"Mike","8","20"},    {"Peter","5","0"}}; 

into the following array:

String [][] myArray = {{"John", "3", "10"}, {"Mike","8","20"}, 
                       {"Paul", "16","2"}, {"Peter","5","0"}};

I have two classes. The first one contains the array, the other one implements Comparator interface. This is the MyArray class:

public class MyArray {
public static void main(String[] args) {
String [][] myArray = {{"John", "3", "10"}, {"Paul", "16","2"}, 
                       {"Mike","8","20"},{"Peter","5","0"}};
ByName byName = new ByName();
Arrays.sort(myArray,byName);
}
}

This is the ByName class:

  import java.util.Comparator;
    public class ByName implements Comparator {
         public int compare(Object o1, Object o2) {
            String name1 = (String)((MyArray) o1)[0]);
            String name2 = (String)((MyArray) o2)[0]);
    return (name1>name2) ? 1 : -1;
// Here I am confused, how can I compare it, how can I sort my array 
// alphabetically by the first element of each element, i.e. by the names. 
            }
    }
1
  • 2
    This would be more straightforward if you had a 1d array of an object with name, num1, num2 fields, then the object could implement comparable. Commented Apr 21, 2013 at 4:11

2 Answers 2

5

You almost got it: instead of < in

return (name1>name2) ? 1 : -1;

use compareTo():

String name1 = ((String[])o1)[0];
String name2 = ((String[])o2)[0];
return name1.compareTo(name2);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank You, but I still got problems in this line: String name1 = (String)((MyArray) o1)[0]); it does not compile
As written, you're not actually comparing MyArray, you're passing in the String[][] itself(first argument to Arrays.sort).
the objects being compared are not of type MyArray. They are String[] each. So just remove that cast as correctly shown in the above answer
@Thomas Yes, that's what OP's doing in his main. I guess there's a confusion between MyArray class and myArray local.
3

You can also use an object of a class instead of the two dimensional arrays:

import java.util.Comparator;
    public class ByName implements Comparator {
         public int compare(Object o1, Object o2) {
            String name1 = (String)(( o1));
            String name2 = (String)((o2));
    return (name1>name2) ? 1 : -1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.