TreeSet集合储存自定义类型元素(实现了Comparable接口)
来源:互联网 发布:暴走大事件禁播了知乎 编辑:程序博客网 时间:2024/06/13 05:44
package com.yingcheng1101.collection.set.treeset;import java.util.TreeSet;public class Set_TreeSet_2 implements Comparable {private String name;private int age;// 对象一创建就需要有年龄与姓名public Set_TreeSet_2(String name, int age) {this.name = name;this.age = age;}// 覆盖toString()public String toString() {return this.name + ":" + this.age;}public int compareTo(Object obj) {// 根据对象的年龄来排序if (!(obj instanceof Set_TreeSet_2)) {// 如果对象不是Set_TreeSet_2类的,抛出运行时异常,结束程序的运行throw new RuntimeException("类型错误");}return this.age - ((Set_TreeSet_2) obj).age;}public static void main(String[] args) {// 让元素自身具备比较的方法,需要元素是实现了Comparable()接口的类的实例TreeSet tree = new TreeSet();tree.add(new Set_TreeSet_2("ddd", 25));tree.add(new Set_TreeSet_2("ccc", 33));tree.add(new Set_TreeSet_2("a", 19));tree.add(new Set_TreeSet_2("bb", 21));System.out.println(tree);}}// [a:19, bb:21, ddd:25, ccc:33]
阅读全文
0 0
- TreeSet集合储存自定义类型元素(实现了Comparable接口)
- TreeSet集合存放自定义类型的对象,可以使用比较器,实现Comparable接口自己设置排序方式
- treeSet添加的元素需要实现comparable接口,否则会出现 类型转换错误
- 黑马程序员------TreeSet集合框架存储自定义元素之排序Comparable与Comparator
- 黑马程序员——TreeSet实现Comparable接口对自定义类排序
- java基础—TreeSet集合中储存自定义对象(java集合二)
- TreeSet是可以对字符串进行排序 的, 因为字符串已经实现了Comparable接口。
- TreeSet的comparable接口
- set集合 HashSet: TreeSet实现Comparable接口,覆盖compareTo方法。 类实现Comparator接口,覆盖compare方法。
- java 集合 实现comparable接口
- 黑马程序员——TreeSet集合储存自定义对象
- TreeSet(有序集合)对Comparable元素的排序(或使用Comparator)与元素equals方法的关系
- Java编程之TreeSet排序两种解决方法(1)元素自身具备比较功能,元素需要实现Comparable接口覆盖compare(2)创建根据自定义Person类的name进行排序的Comparator
- (68)TreeSet练习:两种排序方式:自然排序(实现comparable接口)、比较器
- Java SE TreeSet(实现Comparable接口和Comparator匿名类)根据属性排序示例
- TreeSet实现Comparable接口覆写compareTo()方法
- 集合框架(五)使用Comparable接口和Comparator接口来比较元素
- 使用TreeSet集合比较Comparable接口和Comparator接口的区别
- Nginx配置入门教程
- 11-散列4 Hashing
- 应用服务器集群的Session管理
- jQuery修改CSS伪元素属性的方法
- CSS3 Flexbox布局详解
- TreeSet集合储存自定义类型元素(实现了Comparable接口)
- 自学PHP与培训PHP的到底有多大的差距?
- 代码规范
- 把VMware中的虚拟机导入到Parallels中如何实现
- libfm的基本使用
- 总结:java设计模式之----单例模式singeton
- 【C#
- 我与IDEA的不舍情缘
- 【FastDev4Android框架开发】重写WebView网页加载以及JavaScript注入详解(二十三)