import java.util.Iterator;
import java.util.TreeSet;
class Student3 implements Comparable{
private String name;
private int age;
Student3() { }
Student3(String name,int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int compareTo(Object p) {
int num = new Integer(((Student3)p).getAge()).compareTo(this.getAge());
if (num==0)
return ((Student3)p).getName().compareTo(this.getName());
//这里我返回的是1,不是num,我以为只是影响顺序,没想到竟然去重复失败。为什么呢?
return 1;
}
}
public class Distinct3 {
public static void deleteSame() {
TreeSet<Student3> set = new TreeSet<Student3>();
set.add(new Student3("张三",18));
set.add(new Student3("王五",20));
set.add(new Student3("钱七",20));
set.add(new Student3("孙八",14));
set.add(new Student3("张三",18));
Iterator<Student3> itSet = set.iterator();
while(itSet.hasNext()) {
System.out.println((itSet.next()).getName());
}
}
public static void main(String[] args) {
deleteSame();
}
}
|
|