1. TreeMap(TreeMap<Student,String>)的案例
2. 案例代码:
(1)Student.java:
1 package cn.itcast_04; 2 3 public class Student { 4 private String name; 5 private int age; 6 7 public Student() { 8 super(); 9 } 10 11 public Student(String name, int age) { 12 super(); 13 this.name = name; 14 this.age = age; 15 } 16 17 public String getName() { 18 return name; 19 } 20 21 public void setName(String name) { 22 this.name = name; 23 } 24 25 public int getAge() { 26 return age; 27 } 28 29 public void setAge(int age) { 30 this.age = age; 31 } 32 }
(2)测试类TreeMapDemo2,如下:
1 package cn.itcast_04; 2 3 import java.util.Comparator; 4 import java.util.Set; 5 import java.util.TreeMap; 6 7 /* 8 * TreeMap<Student,String> 9 * 键:Student 10 * 值:String 11 */ 12 public class TreeMapDemo2 { 13 public static void main(String[] args) { 14 // 创建集合对象 15 TreeMap<Student, String> tm = new TreeMap<Student, String>( 16 new Comparator<Student>() { 17 @Override 18 public int compare(Student s1, Student s2) { 19 // 主要条件 20 int num = s1.getAge() - s2.getAge(); 21 // 次要条件 22 int num2 = num == 0 ? s1.getName().compareTo( 23 s2.getName()) : num; 24 return num2; 25 } 26 }); 27 28 // 创建学生对象 29 Student s1 = new Student("潘安", 30); 30 Student s2 = new Student("柳下惠", 35); 31 Student s3 = new Student("唐伯虎", 33); 32 Student s4 = new Student("燕青", 32); 33 Student s5 = new Student("唐伯虎", 33); 34 35 // 存储元素 36 tm.put(s1, "宋朝"); 37 tm.put(s2, "元朝"); 38 tm.put(s3, "明朝"); 39 tm.put(s4, "清朝"); 40 tm.put(s5, "汉朝"); 41 42 // 遍历 43 Set<Student> set = tm.keySet(); 44 for (Student key : set) { 45 String value = tm.get(key); 46 System.out.println(key.getName() + "---" + key.getAge() + "---" 47 + value); 48 } 49 } 50 }
运行效果,如下:
时间: 2024-10-10 03:06:10