TreeSet中的排序问题——Comparable
package com.etc.hashset; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.TreeSet; public class TestHashSet { /** * @param args */ public static void main(String[] args) { Set set=new TreeSet(); set.add(new Student("zhangsan",20)); set.add(new Student("zhangsan",20)); set.add(new Student("zhangsan5",29)); set.add(new Student("zhangsan3",25)); set.add(new Student("zhangsan7",27)); set.add(new Student("zhangsan1",21)); Iterator it = set.iterator(); int num=0; while(it.hasNext()){ System.out.println(num+++"-"+it.next()); } } }
/**
* Comparable是专门用来对TreeSet和TreeMap进行排序用的,comparable是自然排序,所以在对象所在的类实现该接口即可,TreeSet就不需要再指定专门的构造器
*
*/
class Student implements Comparable { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; 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; Student other = (Student) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } public Student() { } public Student(String name, int age) { super(); this.name = name; this.age = 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; } String name; int age; @Override public int compareTo(Object o) { if(o instanceof Student){ Student stu=(Student)o; return this.age-stu.age; } return 0; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } }