TreeSet和TreeMap的排序

1.对于TreeSet要求对数据元素排序,且不可重复
2.TreeMap要求对建值排序
对于TreeSe和TreeMap都是在添加数据时进行排序的。所以要对其设置比较器,例如:
package treeset;

import java.util.Comparator;
import java.util.TreeSet;

public class TreeMapText {

public static void main(String[] args) {
    PeoPle peoPle1=new PeoPle("案件",24);
    PeoPle peoPle2=new PeoPle("案发",23);
    PeoPle peoPle3=new PeoPle("十分",54);
    PeoPle peoPle4=new PeoPle("是个",44);
    TreeSet sTreeSet=new TreeSet(
            new Comparator() {//添加比较器
                @Override
                public int compare(PeoPle o1, PeoPle o2) {                      
                    return o1.getAge()-o2.getAge();//升序排序
                }                   
              }         
            );
    //添加数据时排序
    sTreeSet.add(peoPle1);
    sTreeSet.add(peoPle2);
    sTreeSet.add(peoPle3);
    sTreeSet.add(peoPle4);
    System.out.println(sTreeSet);
    //数据修改不会改变排序的顺序,若修改的数据与原来的数据相同,则会出现数据的重复
   // peoPle1.setAge(10);

}

}

你可能感兴趣的:(java基础)