[javaSE] 集合框架(TreeSet)
2024-08-24 06:46:40
TreeSet:可以对Set集合中的元素排序,默认按照ascii表排序,二叉树结构
左边叉是小的,右边叉是大的
存储自定义对象
定义一个类Student实现Comparable类,使自定义类具备比较性
定义属性年龄age
定义属性姓名name
实现compareTo()方法,传递进来另一个Student对象
判断当前Student对象的age大于另一个Student对象的age,返回1,否则返回-1
获取Student对对象
调用TreeSet对象的add()方法,参数:Student对象
遍历集合
import java.util.TreeSet; public class TreeSetDemo { /**
* @param args
*/
public static void main(String[] args) {
TreeSet<Student> treeset=new TreeSet<Student>();
treeset.add(new Student("taoshihan1",30));
treeset.add(new Student("taoshihan2",20));
treeset.add(new Student("taoshihan3",40));
for(Student student:treeset){
System.out.println(student.name+"==="+student.age);
} } }
class Student implements Comparable<Student>{ public int age;
public String name;
public Student(String name,int age) {
this.name=name;
this.age=age;
}
@Override
public int compareTo(Student o) {
if(o.age<this.age){
return 1;
}else{
return -1;
}
} }
结果:
taoshihan2===20
taoshihan1===30
taoshihan3===40
最新文章
- 【repost】JavaScript 事件模型 事件处理机制
- 天气预报API(四):全国城市代码列表(“新编码”)
- iOS---用LLDB调试,让移动开发更简单(一)
- Introduction to replication 翻译
- SSH框架流程详解
- python基础教程
- J.U.C CAS
- vm12 安装ubuntu15.10详细图文教程 虚拟机安装ubuntu安装 ubuntu更新软件 ubuntu一直卡在下载语言怎么办?
- Netty入门(2) - 核心概念
- 大数据统计分析平台之一、Kafka单机搭建
- bzoj 2055 80人环游世界
- iframe多层嵌套时获取元素
- 7z 7zip 日期、时间,文件名
- 将硬件规定的通信协议用Lua实现(涉及到很多Lua通信的数据转换)
- Qt容器类汇总说明
- ListView - SimpleAdapter 行间颜色交替(转)
- git设置忽略文件和目录
- mysql返回字符串在另外一个字符串中第n次出现的方法。
- 接口规范,js处理json,php返回给ajax的数据格式
- Web Worker 案例