简体   繁体   中英

Java sorting 2d talble error with Arrays.sort()

I am having a little problem with my proggram in java. I need to sort the String array alphabetically depending on the first column. But i am getting a weird error. So here is the code:

import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;

public class Main {

    public static void main(String[] args) throws IOException  {

        String[][] Dictionary= new String[10][2];
        Dictionary[0][0]="a";
        Dictionary[0][1]="5";
        Dictionary[1][0]="c";
        Dictionary[1][1]="6";
        Dictionary[2][0]="b";
        Dictionary[2][1]="2";
        Dictionary[3][0]="f";
        Dictionary[3][1]="8";
        Dictionary[4][0]="z";
        Dictionary[4][1]="9"; //the rest is empty

                              //i want it to be like this:

                              //         a-5
                              //         b-2
                              //         c-6
                              //         f-8
                              //         z-9
                              //         null-null
                              //         null-null
                              //         .
                              //         .
                              //         .

         Arrays.sort(Dictionary, new Comparator<String[]>() {           //<------
                public int compare(final String[] entry1, final String[] entry2) {
                    final String time1 = entry1[0];
                    final String time2 = entry2[0];
                    return time1.compareTo(time2);
                }
            });

    }


}

So at the line where I put the <---- I am getting these 2 errors:

  1. The type Comparator is not generic; it cannot parameterized with arguments

2.Syntax error, parameterized types are only available if source level is 5.0

I am not really sure how the comparator thing works I found it online modified it a bit and its the best I could make out of it but it is still not working. Anyone got any ideas !?

For the java error check : Changing the Java compiler version You need to change the sort method to be like this to accept null :

  Arrays.sort(Dictionary, new Comparator<String[]>() { // <------
                public int compare(final String[] entry1, final String[] entry2) {
                    final String time1 = entry1[0];
                    final String time2 = entry2[0];
                    if (time1 == null) {
                        return 1;
                    } else if (time2 == null) {
                        return -1;
                    }
                    return time1.compareTo(time2);
                }
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM