public class Peoper implements Comparable {
int id;
int age;
String name;
public Peoper(int id, int age, String name) {
super();
this.id = id;
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Peoper [id=" + id + ", age=" + age + ", name=" + name + "]";
}
@Override
public int compareTo(Object o) {
Peoper p;
if (o instanceof Peoper) {
p=(Peoper)o;
}else {
return -1;//-1表示传入的参数比我本身要小
}
int diff=this.id-p.id;
if(diff!=0){
diff=diff/Math.abs(diff);
}
return diff;
}
}
import java.awt.List;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.plaf.synth.SynthScrollBarUI;
public class Demo {
public static void main(String[] args) {
Set set=new TreeSet();
Peoper P1=new Peoper(1, 18, "小明");
Peoper P2=new Peoper(2, 5, "大壮");
Peoper P3=new Peoper(3, 20, "阿强");
set.add(P1);
set.add(P2);
set.add(P3);
Iterator it=set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
上面是两个class,主要是compareTo方法这里看不懂,在Peoper类里这个方法是重写了吧,我不明白为什么这样重写,第一个if和第二个if的功能是啥?还有我尝试不重写,就是方法体力出值写了return 0,结果在Demo运行的时候就只输出了集合的第一个元素,这为啥?还有就是这个compareTo到底在哪里运行了,Demo里没有调用,Peoper里也没有main方法啊?