1、实现Comparator接口,覆盖compare方法
class StringLengthComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
String s1 = (String)obj1;
String s2 = (String)obj2;
int num = new Integer(s1.length()).compareTo(new Integer(s2.length()));
if(num==0)
return s1.compareTo(s2);
return num;
}
}
2、实现Comparable接口,覆盖compareTo方法
class Student implements Comparable
{
private String name;
private int age;
public Student(String name,int age)
{
this.name=name;
this.age=age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public int compareTo(Object obj)
{
if(!(obj instanceof Student))
throw new RuntimeException("不是学生对象!");
Student stu = (Student)obj;
int num = this.age-stu.age;
if(num==0)
return this.name.compareTo(stu.name);
return num;
}
} |
|