zoukankan      html  css  js  c++  java
  • TreeMap的练习(该例需要上例的学生类)

     1 import java.util.*;
    2 class TreeMapTest
    3 {
    4 public static void main(String[] args)
    5 {
    6 TreeMap<Student,String> tm=new TreeMap<Student,String>(new mycompare()); //new TreeMap<Student,String>(); 不带参数的构造函数,Student中 已经写了compareTo 方法比较
    7 tm.put(new Student("lisi01",25),"beijing");
    8 tm.put(new Student("lisi02",22),"tianjing");
    9 tm.put(new Student("lisi02",22),"dongjing"); //put的特点:后者会覆盖前面的value。
    10 tm.put(new Student("lisi04",20),"shanghai");
    11 tm.put(new Student("lisi03",23),"xiamen");
    12
    13 Set<Student> ks=tm.keySet();
    14 for(Iterator<Student> it=ks.iterator();it.hasNext();)
    15 {
    16 Student stu=it.next();
    17 String address=tm.get(stu);
    18 System.out.println(stu.getName()+".."+stu.getAge()+".."+address);
    19 }
    20 /*
    21 Set<Map.Entry<Student,String>> et=tm.entrySet();
    22 for(Iterator<Map.Entry<Student,String>> it=et.iterator();it.hasNext();) //Iterator 泛型别忘了<Map.Entry<Student,String>>
    23 {
    24 Map.Entry<Student,String> me=it.next();
    25 String address=me.getValue();
    26 Student info =me.getKey();
    27 System.out.println(info.getName()+".."+info.getAge()+".."+address);
    28 } */
    29 }
    30 }
    31 class mycompare implements Comparator<Student>
    32 {
    33 public int compare(Student s1,Student s2)
    34 {
    35 // Student s1=(Student)o1;
    36 // Student s2=(Student)o2;
    37 int num= new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
    38 if(num==0)
    39 {
    40 return s1.getName().compareTo(s2.getName()) ;
    41 }
    42 return num;
    43 }
    44 }



  • 相关阅读:
    宏定义中的#
    HDU1506 Largest Rectangle in a Histogram 动态规划
    HDU1864 最大报销额 DP
    POJ2771 Guardian of Decency 最大独立子集
    POJ1698 Alice's Chance 最大流
    HDU1003 Max Sum 动态规划
    eval格式化事件类型的字符串
    C#虚方法virtual详解
    c# 利用反射获得某个类或者对象的所有属性
    windows服务的通常写法
  • 原文地址:https://www.cnblogs.com/pinotao/p/2314878.html
Copyright © 2011-2022 走看看