//仅作为学习笔记
/*
当元素自身不具备比较性,或者具备的比较性不是所需要的
这时需要定义让容器自身具备比较性
定义了比较器,将比较器对象作为参数传递给TreeSet集合的构造函数
当两种排序都存在时,以比较器为主
定义一个类,实现Comparator 接口,覆盖compare方法
当两种排序都存在时,以比较器为主
定义一个类,实现Comparator接口,覆盖compare方法
*/
import java.util.*;
class Student implements Comparable//该接口强制让学生具备比较性
{
private String name;
private int age;
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;
if(this.age < stu.age)
return -1;
if(stu.age == this.age)
return this.name.compareTo(stu.name);//当主要条件相同时 ,也要判断次要条件
return 1;
}
}
class MyCompare implements Comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student)o1;
Student s2 = (Student) o2;
int num = s1.getName().compareTo(s2.getName());
if( num == 0)
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
//return s1.getAge()- s2.getAge();//比较次要条件
return num;
}
}
class TreeSetDemo
{
public static void main(String []args)
{
TreeSet ts = new TreeSet(new MyCompare());
ts.add(new Student("NUM3",33));
ts.add(new Student("NUM2",22));
ts.add(new Student("NUM1",11));
ts.add(new Student("NUM4",44));
ts.add(new Student("NUM4",45));
Iterator it = ts.iterator();
while( it.hasNext())
{
Student s = (Student)it.next();
sop( s.getName() + " "+ s.getAge());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
/*
练习:
按照字符串长度排序
字符串本身具备比较性,但是它的比较方式不是所需要的
这时就只能使用比较器
*/
import java.util.*;
class TreeSetDemo
{
public static void main(String []args)
{
TreeSet ts = new TreeSet(new MyCompare());
ts.add("adfa");
ts.add("afafq");
ts.add("aazbjhafafidhb");
ts.add("aba");
Iterator it = ts.iterator();
while(it.hasNext())
{
sop(it.next());
}
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
class MyCompare implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1 = (String)o1;
String s2 = (String)o2;
int num = s1.length()-s2.length();
if( num == 0)
return s1.compareTo(s2);
return num;
}
}