当前位置:编程学习 > JAVA >>

JAVA中用Set集合的TreeSet类对姓名和编号排序

在Per类中以内部类形式实现比较器PerComparator,在写比较器前要实现compareTo方法,谁能告诉我?
答案:按编号的排序,compareTo比较一下就可以了:

import java.util.Iterator;
import java.util.TreeSet;

public class PriorityTest extends TreeSet<PriorityTest.Test>{
static class Test implements Comparable<Test>{
String name;
int num;

public Test(String name, int num) {
this.name = name;
this.num = num;
}

public int compareTo(Test arg) {
if(num < arg.num)
return 1;
else if(num > arg.num)
return -1;
else
return 0;
}

public String toString(){
return name;//Character.toString(arg0)
}
}

public void add(String str, int priority){
super.add(new Test(str,priority));
}

public static void main(String args[]){
PriorityTest pTest = new PriorityTest();
pTest.add("小明1",1);
pTest.add("小红3",3);
pTest.add("小张2",2);



for(Iterator iter = pTest.iterator();iter.hasNext();){
Object obj = iter.next();
System.out.println(obj);
}
}
}

定义内部类. 至于里面怎么比较,就看具体的情况了,这里只随便比较一下name

public class Per{

private String name;

private class PerComparator implements Comparator

public int compareTo(Object obj1, Object obj2){

return ((Per)obj1.getName().hashCode()-(Per).getName().hashCode());

}

public String getName(){

return name;

}

}

上一个:C#和java用法上有那些不同,那些相同
下一个:Java缂栫▼锛氬綋鐢ㄦ埛杈撳叆涓嶆槸鏁板瓧鏃跺浣曞惊鐜姹傝緭鍏ユ暟瀛楋紵 - 宸茶В鍐?- 鎼滄悳闂棶

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,