初始化的集合:
22012 王先生
22015 马先生
22016 李先生
22018 王小姐
22020 尹先生
截取前面部分得到的集合:
22012 王先生
22015 马先生
22016 李先生
截取后面部分得到的集合:
22018 王小姐
22020 尹先生
在使用由TreeSet类实现的Set集合时,也可以通过单独的比较器对集合中的对象进行排序。
比较器既可以作为一个单独的类,也可以作为对应类的内部类,本例中移内部类的形式实现比较器。
import java.util.Comparator;
public class Person implements Comparable{
private String name;
private long id_card;
public Person(String name,long id_card){
this.name = name;
this.id_card = id_card;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public long getId_card(){
return id_card;
}
public void setId_card(long id_card){
this.id_card = id_card;
}
public int compareTo(Object o){//默认按编号升序排序
Person person = (Person)o;
int result = id_card>person.id_card 1:(id_card==person.id_card 0:-1);
return result;
}
static class PersonComparator implements Comparator{
public static final int NAME = 1;
public static final int ID_CARD = 2;
private int orderByColumn = 1;//默认为按姓名排序
public static final boolean ASC = true;
public static final boolean DESC = false;
private boolean orderByMode = true;//默认为按升序排序
public int compare(Object o1,Object o2){//实现Comparator接口的方法
Person p1 = (Person)o1;
Person p2 = (Person)o2;
int result = 0;//默认的判断结果为两个对象相等
switch(orderByColumn){//判断排序条件
case 1:
String s1 = CnToSpell.getFullSpell(p1.getName());
String s2 = CnToSpell.getFullSpell(p2.getName());
if(orderByMode){//升序
result = s1.compareTo(s2);
}
else{//降序
result = s2.compareTo(s1);
}
break;
case 2:
if(orderByMode){//升序
result = (int)(p1.getId_card()-p2.getId_card());
}
else{//降序
result = (int)(p2.getId_card()-p1.getId_card());
}
break;
}
return result;
}
public void orderByColumn(int orderByColumn){//用来设置排序条件
this.orderByColumn = orderByColumn;
}
public void orderByMode(boolean orderByMode){//用来设置排序方式
this.orderByMode = orderByMode;
}
}
}
import java.util.*;
public class TestSet{
public static void main(String args[]){
TreeSet
treeSet1 = new TreeSet
(); Person p1 = new Person("马先生",22015); Person p2 = new Person("李先生",22016); Person p3 = new Person("王小姐",22018); treeSet1.add(p1); treeSet1.add(p2); treeSet1.add(p3); System.out.println("客户化排序前,默认按编号升序排序:"); //新创建一个Set集合,不进行客户化排序,默认按编号升序排序 Tre