关于set方法的使用和Comparator接口的使用
public class Person implements Comparable{ int id;
int age;
String name;
public Person(int id, int age, String name) {
super();
this.id = id;
this.age = age;
this.name = name;
}
public String toString() {
return "Person [id=" + id + ", age=" + age + ", name=" + name + "]";
}
public int compareTo(Object o) {
Person p;
if(o instanceof Person) {
p=(Person)o;
}else {
return -1;
}
int diff=this.id-p.id;
if(diff!=0) {
diff=diff/Math.abs(diff);
}
return diff;
}
}
//////////上面的是person类/////////
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class Demo {
public static void main(String[] args) {
Set set=new TreeSet();
Person p1=new Person(1,18,"小明");
Person p2=new Person(3,17,"小明");
Person p3=new Person(2,15,"小李");
set.add(p1);
set.add(p2);
set.add(p3);
System.out.println(set.size());
Iterator it=set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
//////下面的是dome类(包含主程序入口)//////////
下面是打印结果
3
Person [id=1, age=18, name=小明]
Person [id=2, age=15, name=小李]
Person [id=3, age=17, name=小明]
我想问的是主程序中是如果调用了person类中的方法啊,定义了person对象,但并没有调用方法,整个程序给我感觉一脸懵的感觉。