Mega Code Archive

 
Categories / Java Tutorial / Collections
 

Implementing a Comparator for a class

import java.util.Arrays; import java.util.Comparator; class CompTypeComparator implements Comparator {   public int compare(Object o1, Object o2) {     int j1 = ((Integer) o1);     int j2 = ((Integer) o2);     return (j1 < j2 ? -1 : (j1 == j2 ? 0 : 1));   } } public class MainClass {   public static void main(String[] args) {     Integer[] a = new Integer[10];     for (int i = 0; i < a.length; i++) {       a[i]= i;     }     System.out.println("before sorting, a = " + Arrays.asList(a));     Arrays.sort(a, new CompTypeComparator());     System.out.println("after sorting, a = " + Arrays.asList(a));   } } /**/ before sorting, a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] after sorting, a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]