TreeSet+LinkedHashSet+Comparable+Hashcode+Equals

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public class TestTreeSet {

 public static void main(String[] args) {
  // reSortTreeset();
  reSortLinkedHashSet();
 }

 private static void reSortTreeset() {
  Set<People> tempTs = new TreeSet<People>();
  tempTs.add(new People("baa", 2));
  tempTs.add(new People("abc", 1));
  tempTs.add(new People("acb", 1));
  tempTs.add(new People("bba", 1));
  tempTs.add(new People("aaa", 1));
  tempTs.add(new People("aaa", 2));
  tempTs.add(new People("baa", 1));

  Iterator<People> it = tempTs.iterator();
  while (it.hasNext()) {
   People mes = (People) it.next();
   System.out.println(mes.name + " " + mes.age);
  }

 }

 private static void reSortLinkedHashSet() {
  LinkedHashSet<People> tempTs = new LinkedHashSet<People>();
  tempTs.add(new People("baa", 2));
  tempTs.add(new People("abc", 1));
  tempTs.add(new People("acb", 1));
  tempTs.add(new People("bba", 1));
  tempTs.add(new People("aaa", 1));
  tempTs.add(new People("aaa", 2));
  tempTs.add(new People("baa", 1));

  Iterator<People> it = tempTs.iterator();

  while (it.hasNext()) {
   People mes = (People) it.next();

   System.out.println(mes.name + " " + mes.age);
  }
 }

}

class People implements Comparable {
 People(String name, int age) {
  this.name = name;
  this.age = age;
 }

 String name;
 int age;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 int i = 0;

 @Override
 public int hashCode() {
  int x = 3;
  int y = 5;
  for (int i = 1; i < 5; i++) {
   x = x * x + y;
   y = x + y;
  }
  return x * y;
 }

 public boolean equals(Object obj) {
  if (!(obj instanceof People)) {
   return false;
  }
  if (obj == null) {
   return false;
  }
  if (this == obj) {
   return true;
  }
  if (this.getAge() == ((People) obj).getAge()) {
   if (this.getName().equals(((People) obj).getName())) {
    return true;
   }
   return false;
  }
  return false;
 }

 public String toString() {
  return name + " " + String.valueOf(age);
 }

 // 覆蓋Comparable接口的compareTo方法
 @Override
 public int compareTo(Object o) {
  if (this.getName().compareTo(((People) o).getName()) > 0) {
   return 1;
  }
  if (this.getName().compareTo(((People) o).getName()) < 0) {
   return -1;
  }

  return this.getAge() - ((People) o).getAge();

 }

}
如果People類不實現Comparable接口中的compareTo()方法則會報錯:

Exception in thread "main" java.lang.ClassCastException: People cannot be cast to java.lang.Comparable
 at java.util.TreeMap.put(TreeMap.java:542)
 at java.util.TreeSet.add(TreeSet.java:238)
 at TestTreeSet.reSortTreeset(TestTreeSet.java:16)
 at TestTreeSet.main(TestTreeSet.java:9)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章