Java TreeSet add Comparable custom objects

Description

Java TreeSet add Comparable custom objects

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

class Language implements Comparable<Language> {
  private String name;

  private int id;

  public String getName() {
    return name;/*from  w  ww  .ja v a  2s . com*/
  }

  public int getId() {
    return id;
  }

  Language(String str, int id) {
    name = str;
    this.id = 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", 1));
    prodList.add(new Language("HTML", 0));
    prodList.add(new Language("Java", 2));
    prodList.add(new Language("Javascript", 4));

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



PreviousNext

Related