黑马程序员技术交流社区
标题:
TreeSet两种比较器部分程序
[打印本页]
作者:
myself123
时间:
2015-8-24 17:53
标题:
TreeSet两种比较器部分程序
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;
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2