一.TreeSet类中的元素必须是可“排序”的,所以必须实现接口implements Comparable类,重写compare()方法;
package ch3;
public class Student implements Comparable {
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
Student s =(Student)o;
return age-s.age;
}
private int age;
private String name;
Student(int num,String name)
{
this.age =num;
this.name =name;
}
@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
Student s =(Student)o;
return age ==s.age&&name.equals(s.name);
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return age*name.hashCode();
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "age:" +age+"name:"+name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package ch3;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class TreeSetText {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Set ts = new TreeSet();
Student s1 = new Student(18,"zhj");
Student s2 = new Student(25,"zyj");
Student s3 = new Student(28,"xml");
Student s4 = new Student(18,"zah");
Student s5 = new Student(18,"zah");//没有s4,s5
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
Iterator in = ts.iterator();
while(in.hasNext())
{
System.out.println(in.next());
}
}
}