0

I have the following code. When I try to compile it, it gives me the following error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method sort(T[], Comparator) in the type Arrays is not applicable for >the arguments (int[][], new Comparator(){})

at test.main.main(main.java:12)


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

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

        int [][] A = {{1,2,3}, {2,3,4}, {3,4,5}};

        Arrays.sort(A, new Comparator<Integer[]>() {
            public int compare(Integer[] int1, Integer[] int2) {
                Integer key1 = int1[2];
                Integer key2 = int2[2];
                return key1.compareTo(key2);
            }
        });


        for(int i=0; i<3; i++) {
            System.out.println(A[i][0] + ", " + A[i][1] + ", " + A[i][2]);
        }

    }
}

How can I solve this problem

2 Answers2

2

You can solve this problem using

Integer[][] A = ...;

instead of

int[][] A = ...;

You can get more information in this post: Why can Java Collections not directly store Primitives types?.

Community
  • 1
  • 1
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

You need not call Arrays.sort(Integer[], Comparator); Instead you can directly call Arrays.sort(int[]);.

Actually Integer has already implemented Comparable, therefore you may not define it again, until an unless you want to define some different sorting style!

Sourabh Bhat
  • 1,793
  • 16
  • 21