Java Comparable implement for TreeSet

Description

Java Comparable implement for TreeSet

import java.util.Set;
import java.util.TreeSet;

class Language implements Comparable<Language> {
  String name;//from w w  w  .  j a v a2s.c  o  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[]) {
    Set<Language> prodList = new TreeSet<Language>();

    prodList.add(new Language("CSS", 3));
    prodList.add(new Language("HTML", 6));
    prodList.add(new Language("Java", 1));
    prodList.add(new Language("Javascript", 4));

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



PreviousNext

Related