import java.util.*;
public class UpdateStu implements Comparable {
String name;
long id;
public UpdateStu(String name, long id) {
this.id = id;
this.name = name;
}
public int compareTo(Object o) { //compareTo方法中的前兩行代碼什麼意思
UpdateStu upstu = (UpdateStu) o;
int result = id > upstu.id ? 1 : (id == upstu.id ? 0 : -1);
return result;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
UpdateStu stu1 = new UpdateStu("李同學", 01011);
UpdateStu stu2 = new UpdateStu("陳同學", 01021);
UpdateStu stu3 = new UpdateStu("王同學", 01051);
UpdateStu stu4 = new UpdateStu("馬同學", 01012);
TreeSet tree = new TreeSet<>();
tree.add(stu1);
tree.add(stu2);
tree.add(stu3);
tree.add(stu4);
Iterator it = tree.iterator();
System.out.println("Set集合中的所有元素:");
while (it.hasNext()) {
UpdateStu stu = (UpdateStu) it.next();
System.out.println(stu.getId() + " " + stu.getName());
}
it = tree.headSet(stu2).iterator();
System.out.println("截取前面部分的集合:");
while (it.hasNext()) {
UpdateStu stu = (UpdateStu) it.next();
System.out.println(stu.getId() + " " + stu.getName());
}
it = tree.subSet(stu2, stu3).iterator();
System.out.println("截取中間部分的集合");
while (it.hasNext()) {
UpdateStu stu = (UpdateStu) it.next();
System.out.println(stu.getId() + " " + stu.getName());
}
}
}
就是用自己的id,和傳入對象的id做比較;
如果自己的id大於upstu的id,那麼值為1,否則再判斷是否相等,如果相等則值為0,否則為-1;
這是一個三目運算符。
希望能夠幫到你...