Java Arrays sort custom object via Comparable

Description

Java Arrays sort custom object via Comparable



import java.util.Arrays;

class Language implements Comparable<Language> {
  String name;//ww w.  jav a 2 s .  c om

  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