Java Comparator implement

Description

Java Comparator implement

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

class Language implements Comparable<Language> {
  String name;//from  www .j a  v a 2 s . co  m

  int prodID;

  Language(String str, int id) {
    name = str;
    prodID = id;
  }
  
  public String getName() {
    return name;
  }

  public int getProdID() {
    return prodID;
  }

  public int compareTo(Language p2) {
    return name.compareToIgnoreCase(p2.name);
  }

  public boolean equals(Object p2) {
    return name.compareToIgnoreCase(((Language) p2).name) == 0;
  }
}
class MyComparator implements Comparator<Language> {
  public int compare(Language emp1, Language emp2) {
    int nameComp = new Integer(emp1.getProdID()).compareTo(emp2.getProdID());
    return ((nameComp == 0) ? emp1.getName().compareTo(emp2.getName()) : nameComp);
  }
}
public class Main {
  public static void main(String args[]) {
    Language[] prodList = {
        new Language("Java", 1), 
        new Language("HTML", 6), 
        new Language("CSS", 3), 
        new Language("Javascript", 4) };
    

    for (Language p : prodList)
      System.out.printf("%-14s ID: %d\n", p.name, p.prodID);

    Arrays.sort(prodList);
    System.out.println();
    
    for (Language p : prodList)
      System.out.printf("%-14s ID: %d\n", p.name, p.prodID);

    Arrays.sort(prodList,new MyComparator());
    System.out.println();
    
    for (Language p : prodList)
      System.out.printf("%-14s ID: %d\n", p.name, p.prodID);

  }
}



PreviousNext

Related