您的位置:首页 > 其它

Treeset树集适用于数据的排序;树映射TreeMap,必须保证节点中的关键字是升序排列的

2009-11-21 16:53 295 查看
package com.fuxi.test.collection;
/**
* Treeset树集适用于数据的排序;树映射TreeMap,必须保证节点中的关键字是升序排列的
* 此例是分别按着学生的英语成绩和数学成绩排序
*/
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;

public class TreeMapTest {

public static void main(String[] args) {
TreeMap<StudentKey, Student3> map = new TreeMap<StudentKey, Student3>();
String str[] = {"zhangyi","zhanger","zhangsan","zhangsi"};
double math[] = {89,78,98,21};
double english[] = {43,53,64,23};
Student3 student[] = new Student3[4];
for(int i = 0;i<student.length;i++){
student[i] = new Student3(str[i],math[i],english[i]);
}
StudentKey key[] = new StudentKey[4];
for(int i = 0;i<key.length;i++){
key[i] = new StudentKey(student[i].math);
}
for(int i = 0;i<student.length;i++){
map.put(key[i], student[i]);
}
int number = map.size();
System.out.println("树映射中有"+number+"个对象,按数学成绩排序:");
Collection<Student3> collection = map.values();
Iterator<Student3> it = collection.iterator();
while(it.hasNext()){
Student3 stu = it.next();
System.out.println("姓名"+stu.name+"数学"+stu.math);
}
map.clear();
for(int i = 0;i<key.length;i++){
key[i] = new StudentKey(student[i].english);
}
for(int i =0;i<student.length;i++){
map.put(key[i], student[i]);
}
number = map.size();
System.out.println("树映射中有"+number+"个对象:按英语成绩排序:");
Collection<Student3> collection2 = map.values();
Iterator<Student3> it2 = collection2.iterator();
while(it2.hasNext()){
Student3 stu = it2.next();
System.out.println("姓名:"+stu.name+"英语"+stu.english);
}
}
}
class StudentKey implements Comparable{
double d = 0;
public StudentKey(double d){
this.d =d ;
}
public int compareTo(Object b) {
StudentKey st = (StudentKey) b;
if((this.d-st.d)==0){
return -1;
}else{

return (int) ((this.d-st.d)*1000);
}
}

}
class Student3{
String name;
double math,english;
public Student3(String name,double math,double english){
this.english = english;
this.name = name;
this.math = math;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐