1、Comparable接口生命了一个比较两个对象大小的comparaTo()方法。
例如:
public class Edge implements Comparable<Edge>{
public int a;
public int b;
public int cost;
@Override
public int compareTo(Edge e) {
if(e.cost>this.cost){
return -1;
}else if(e.cost==this.cost){
return 0;
}
else{
return 1;
}
}
}
2、Comparator接口在优先级列表中用到,作为参数传递,里面的方法是compare()。后来又在treemap中的构造函数中遇到。如:TreeMap(Comparator<? super K> comparator)
构造一个新的、空的树映射,该映射根据给定比较器进行排序。那treeSet也是一样:TreeSet(Comparator<? super E> comparator)
构造一个新的空 TreeSet,它根据指定比较器进行排序。
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class test {
private String name;
private int population;
public test(String name, int population)
{
this.name = name;
this.population = population;
}
public String getName()
{
return this.name;
}
public int getPopulation()
{
return this.population;
}
public String toString()
{
return getName() + " - " + getPopulation();
}
public static void main(String args[])
{
Comparator<test> OrderIsdn = new Comparator<test>(){
public int compare(test o1, test o2) {
// TODO Auto-generated method stub
int numbera = o1.getPopulation();
int numberb = o2.getPopulation();
if(numberb > numbera)
{
return 1;
}
else if(numberb<numbera)
{
return -1;
}
else
{
return 0;
}
}
};
Queue<test> priorityQueue = new PriorityQueue<test>(11,OrderIsdn);
test t1 = new test("t1",1);
test t3 = new test("t3",3);
test t2 = new test("t2",2);
test t4 = new test("t4",0);
priorityQueue.add(t1);
priorityQueue.add(t3);
priorityQueue.add(t2);
priorityQueue.add(t4);
System.out.println(priorityQueue.poll().toString());
}
}