// 定一个实体类Student
import java.util.Comparator;
public class Student implements Comparable{
public static final Comparator NAME_COMPARATOR=new NameComparator();
public static final Comparator AGE_COMPARATOR=new AgeComparator();
private String name;
private int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age) {
super();
this.name = name;
this.age = 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;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Student)
{
Student s=(Student)obj;
if(s.name.equals(this.name)&&s.age==this.age)
{
return true;
}
}
return false;
}
@Override
public int hashCode() {
final int prime=71;
int result=1;
result=prime*result;
result=prime*result+age;
result=prime*result+((name==null)? 0:name.hashCode());
return result;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.name +":"+this.age;
}
//compareTo 是Comparable接口中的方法,用来判断实现该接口类的对象的大小
public int compareTo(Object arg) {
Student s=(Student)arg;
if(this.age==s.age)
return this.name.compareTo(s.name);
return this.age-s.age;
}
static class NameComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
Student s1=(Student)obj1;
Student s2=(Student)obj2;
return s1.getName().compareTo(s2.getName());
}
}
static class AgeComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
Student s1=(Student)obj1;
Student s2=(Student)obj2;
return s1.age-s2.age;
}
}
}
//用SortedSet集合来体现Comparator、Comparable 的区别
public class ArraySortedSetTest {
public static void main(String[] args) {
// 1、该 set 根据其元素的自然顺序进行排序。(根据Student类的CompareTo方法进行排序)
//SortedSet set=new ArraySortedSet();
// 2、set2根据指定比较器(MyComparator)进行排序
//SortedSet set=new ArraySortedSet(new MyComparator());
// 3、set3 set4 是将自己定义的比较器写进Student类中 并可以定义不同的比较条件(多个比较器)
SortedSet set3=new ArraySortedSet(Student.NAME_COMPARATOR);
SortedSet set=new TreeSet(Student.AGE_COMPARATOR);
set.add(new Student("张三",20));
set.add(new Student("老师",23));
set.add(new Student("老是",21));
set.add(new Student("xxx",20));
Iterator it=set.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
Student s1=(Student)obj1;
Student s2=(Student)obj2;
return s1.getName().compareTo(s2.getName());
}
}
|