title: How to implement a TreeSet in Java?
body: <p>I'm implementing a TreeSet which will sort by person's age, but a person will not be saved in set if person's name is equals. I implement equals and hashcode, but this set will save all persons even if they have the same name. I don't know why.</p>
  
  <pre><code>public class Person implements Comparable&lt;Person&gt;{
      private String name;
      private int age;
  
      public Person(String name, int age){
          this.name = name;
          this.age = age;
      }
  
      @Override
      public int compareTo(Person o) {
          if(this.getAge()&lt;o.getAge()){
              return -1;
          }
          return this.getAge() == o.getAge()?0:1;
      }
  
      @Override
      public boolean equals(Object object){
          return name.equals(((Person)object).getName());
      }
  
      @Override
      public int hashCode(){
          return name.hashCode();
      }
  
      public String getName() {
          return name;
      }
  
      public int getAge() {
          return age;
      }
  
      @Override
      public String toString() {
          return "Person [name=" + name + ", age=" + age + "]";
      }
  
      public static void main(String[] args){
          Set&lt;Person&gt; set = new TreeSet&lt;Person&gt;();
          set.add(new Person("Jack",30));
          set.add(new Person("Jack",20));
          System.out.println(set);
      }
  }
  </code></pre>