Java_基础—TreeMap集合键是Student值是String的案例
来源:互联网 发布:全志科技 知乎 编辑:程序博客网 时间:2024/05/18 01:01
Student类,属性为name,age
实现接口Comparable,重写comparTo()方法,通过年龄的大小进行排序实现
public class Student implements Comparable<Student>{ @Override public int compareTo(Student o) { int num = this.age - o.age; return num == 0 ? this.name.compareTo(o.name) : num; } }
TreeMap类
package com.soar.map;import java.util.Comparator;import java.util.TreeMap;import com.soar.bean.Student;public class Demo7_TreeMap { /* * * A:案例演示 * TreeMap集合键是Student值是String的案例 */ public static void main(String[] args) { //comparator(); TreeMap<Student,String> tm = new TreeMap<>(new Comparator<Student>(){ @Override public int compare(Student s1, Student s2) { int num = s1.getName().compareTo(s2.getName()); //按照姓名的Unicode码比较 return num == 0 ? s1.getAge() - s2.getAge() : num; } }); tm.put(new Student("张三",23),"北京"); tm.put(new Student("李四",24),"上海"); tm.put(new Student("王五",25),"广州"); tm.put(new Student("赵六",26),"深圳"); System.out.println(tm); //在Student对象类中重写comparTo方法,按照年龄的大小比较进行排序 } private static void comparator() { TreeMap<Student,String> tm = new TreeMap<>(); tm.put(new Student("张三",23),"北京"); tm.put(new Student("李四",24),"上海"); tm.put(new Student("王五",25),"广州"); tm.put(new Student("赵六",26),"深圳"); System.out.println(tm); }}
阅读全文
0 0
- Java_基础—TreeMap集合键是Student值是String的案例
- TreeMap集合键是Student值是String的案例
- HashMap集合键是Student值是String的案例
- 集合框架_HashMap集合键是String值是Student的案例
- 集合框架_HashMap集合键是Student值是String的案例
- 集合框架_TreeMap集合键是Student值是String的案例
- 集合框架_TreeMap集合键是String值是String的案例
- 集合框架_HashMap集合键是Stirng值是String的案例
- 集合框架_HashMap集合键是Integer值是String的案例
- 用java编写TreeMap<Student,String>集合,存储的元素按照年龄进行排序
- Java_基础—集合的总结
- java 集合 TreeMap 键是对象,TreeMap中要重写compareTo方法
- 集合之TreeMap案例
- struct 后面的 student 是结构标记
- Java_基础—Collection集合的基本功能测试
- Java_基础—Collection集合的带All功能测试
- Java_基础—集合的遍历之迭代器遍历
- Java_基础—Map集合的功能概述
- oracle 两个字符串根据指定分割符分割后比较方法
- 图论之拓扑排序
- Python函数的高级特性
- POJ 3058 Decompression 笔记
- 如何解决Errors occurred during the build.
- Java_基础—TreeMap集合键是Student值是String的案例
- 时间调度的架构
- 掌握flash的as3图形学Stage3d的屏幕坐标和纹理UV采样坐标
- SPOJ Fast Maximum Matching(二分图最大匹配Hopcroft-Carp)
- 终端提交代码到码云
- 【刷题】从1到n整数中1出现的次数
- React学习(七)获取真实的DOM节点
- (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escap
- 选择器总结