Java SortedSet create via TreeSet

Description

Java SortedSet create via TreeSet

import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;

public class Main {
  public static void main(String[] args) {
    Language a1 = new Language("CSS", 1);
    Language a2 = new Language("CSS3", 2);
    Language a3 = new Language("CSS2", 3);
    Language b1 = new Language("HTML", 1);
    Language b2 = new Language("HTML5", 2);
    Language b3 = new Language("Java", 4);
    Language b4 = new Language("C#", 4);
    //from   w ww . j a  va  2s. co  m
    Language nullLevel = new Language("CSS", null);
    Language nullName = new Language(null, 2);
    SortedSet<Language> set = new TreeSet<Language>();
    set.add(a1);
    set.add(a2);
    set.add(a3);
    set.add(b1);
    set.add(b2);
    set.add(b3);
    set.add(b4);
    set.add(nullLevel);
    set.add(nullName);
    System.out.println(Arrays.toString(set.toArray()));
  }
}

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

  public Language(String name, Integer level) {
    this.name = name;
    this.level = level;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((level == null) ? 0 : level.hashCode());
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    Language other = (Language) obj;
    if (level == null) {
      if (other.level != null)
        return false;
    } else if (!level.equals(other.level))
      return false;
    if (name == null) {
      if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
      return false;
    return true;
  }

  @Override
  public int compareTo(Language o) {
    if (level == null) {
      return new Language(name, 0).compareTo(o);
    }
    if (name == null) {
      return new Language("", level).compareTo(o);
    }

    if (level.equals(o.level)) {
      return name.compareTo(o.name);
    } else {
      return level.compareTo(o.level);
    }
  }

  public String toString() {
    return level + " " + name;
  }

}



PreviousNext

Related