Java TreeSet store custom Comparable object

Description

Java TreeSet store custom Comparable object

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

public class Main{
  public static void main(String[] args) {
    Set<Language> set = new TreeSet<Language>();

    set.add(new Language("CSS", 1));
    set.add(new Language("HTML", 5));
    set.add(new Language("Java", 10));
    set.add(new Language("Javascript", 4));
    set.add(new Language("SQL", 3));
    set.add(new Language("C++", 5));
    set.add(new Language("C", 15));
    set.add(new Language("Dart", 225));
    set.add(new Language("C#", 225));
    for (Language f : set) {
      System.out.println(f);//from  www. j a  v a  2  s.  c o  m
    }
  }
} 

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

  public Language(String name, int freq) {
    this.name = name;
    this.freq = freq;
  }
  @Override
  public boolean equals(Object o) {
    if (o == null) return false;
    if (o.getClass().isAssignableFrom(Language.class)) {
      Language other = (Language)o;
      return other.freq == this.freq && other.name.equals(this.name);
    } else {
      return false;
    }
  }

  @Override
  public int compareTo(Language other) {
    if (freq == other.freq) {
      return name.compareTo(other.name);
    } else {
      return freq - other.freq;
    }
  }
  @Override
  public String toString() {
    return name + ":" + freq;
  }
}



PreviousNext

Related