Compare2DArray.java Source code

Java tutorial

Introduction

Here is the source code for Compare2DArray.java

Source

import java.util.Arrays;
import java.util.Comparator;

class Compare2DArray implements Comparator {
    public int compare(Object a, Object b) {
        int aa[] = (int[]) a;
        int bb[] = (int[]) b;
        for (int i = 0; i < aa.length && i < bb.length; i++)
            if (aa[i] != bb[i])
                return aa[i] - bb[i];
        return aa.length - bb.length;
    }
}

public class Main {
    public static void main(String args[]) {
        int d2[][] = { { 11, 43 }, { 6, 98 }, { 44, 38 }, { 11, 4 }, { 17, 32 } };
        Arrays.sort(d2, new Compare2DArray());
        for (int i = 0; i < d2.length; i++) {
            for (int j = 0; j < d2[i].length; j++)
                System.out.print(d2[i][j] + " ");
            System.out.println();
        }
    }
}