Java Comparable implement for Arrays.sort()

Description

Java Comparable implement for Arrays.sort()


import java.util.Arrays;

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

  int prodID;

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

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

  public boolean equals(Object p2) {
    return name.compareToIgnoreCase(((Language) p2).name) == 0;
  }
}

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);
  }
}



PreviousNext

Related