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

 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;
  }
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值