标签:string yun main return package vat ring pack static
自定义比较策略的方法:
1.先自定义一个比较器的类,在类中实现Comparator接口
2.在类中重写compare()方法
3.将自定义的比较器的一个实例作为构造方法的参数传入,则TreeSet就按照构造方法传入的比较器的比较策略对TreeSet的元素进行排序
========================================
package cn.yunhe.collection.set;
import java.util.Set;
import java.util.TreeSet;
import cn.yunhe.collection.util.ComparatorAce;
import cn.yunhe.collection.util.ComparatorDsce;
import cn.yunhe.collection.util.StudentList;
public class TreeSet3 {
public static void main(String[] args) {
/**
* 正序
*/
Set<StudentList> tre = new TreeSet<StudentList>(new ComparatorAce());
tre.add(new StudentList(1003, "tom"));
tre.add(new StudentList(1001, "jack"));
tre.add(new StudentList(1004, "lilie"));
tre.add(new StudentList(1002, "james"));
for (StudentList stu : tre) {
System.out.println(stu.getId() + "," + stu.getName());
}
System.out.println("=============================");
/**
* 倒序
*/
Set<StudentList> tre1 = new TreeSet<StudentList>(new ComparatorDsce());
tre1.add(new StudentList(1003, "tom"));
tre1.add(new StudentList(1001, "jack"));
tre1.add(new StudentList(1004, "lilie"));
tre1.add(new StudentList(1002, "james"));
for (StudentList stu : tre1) {
System.out.println(stu.getId() + "," + stu.getName());
}
==========================================
// 实现正序的比较器
package cn.yunhe.collection.util;
import java.util.Comparator;
public class ComparatorAce implements Comparator<StudentList>{
public int compare( StudentList o1, StudentList o2) {
if(o1.getId()>=o2.getId()){
return 1;
}else{
return -1;
}
}
}
============================================
//实现倒序的比较器
package cn.yunhe.collection.util;
import java.util.Comparator;
public class ComparatorDsce implements Comparator<StudentList> {
@Override
public int compare(StudentList o1, StudentList o2) {
if (o1.getId() >= o2.getId()) {
return -1;
} else {
return 1;
}
}
}
=============================
//学生类
package cn.yunhe.collection.util;
public class StudentList {
/**
* 定义属性
*/
private int id;
private String name;
/**
* 构造方法
*/
public StudentList() {
super();
}
public StudentList(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Collection接口下的Set接口TreeSet类中的自定义比较策略
标签:string yun main return package vat ring pack static
原文地址:https://www.cnblogs.com/pyobbiwitwsai/p/9520217.html