请问 比较对象主次条件时, 实现 Comparable 接口 覆盖其中的queals()方法,compareTo()方法 与 实现 comparator 接口 覆盖 compare()有什么区别?
参考代码
import java.util.*;
public class GenericDemo03
{
public static void main(String[] args)
{
TreeSet<Person04> ts = new TreeSet<Person04>(new MyCom1());
ts.add(new Person04("lisi01",30));
ts.add(new Person04("lisi02",32));
ts.add(new Person04("lisi06",10));
ts.add(new Person04("lisi07",33));
Iterator<Person04> it =ts.iterator();
while(it.hasNext())
{
Person04 p = it.next();
System.out.println(p.getName()+"..."+p.getAge());
}
}
}
class MyCom1 implements Comparator<Person04>
{
public int compare(Person04 p1, Person04 p2)
{
int num= p1.getAge() -p2.getAge();
return num==0?p1.getName().compareTo(p2.getName()):num;
}
}
class Person04
{
private String name;
private int age;
Person04(String name, int age)
{
this.name = name;
this.age = age;
}
public int compareTo(Person04 obj)
{
Person03 p = (Person03)obj;
int num = this.age - p.age;
return num==0?this.name.compareTo(p.name):num;
}
public boolean equals(Object obj)
{
if(this==obj)
return true;
if(!(obj instanceof Person04))
return false;
Person03 p = (Person04)obj;
return this.name.equals(p.name) &&this.age==p.age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|