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

最新文章

  1. 【repost】JavaScript 事件模型 事件处理机制
  2. 天气预报API(四):全国城市代码列表(“新编码”)
  3. iOS---用LLDB调试,让移动开发更简单(一)
  4. Introduction to replication 翻译
  5. SSH框架流程详解
  6. python基础教程
  7. J.U.C CAS
  8. vm12 安装ubuntu15.10详细图文教程 虚拟机安装ubuntu安装 ubuntu更新软件 ubuntu一直卡在下载语言怎么办?
  9. Netty入门(2) - 核心概念
  10. 大数据统计分析平台之一、Kafka单机搭建
  11. bzoj 2055 80人环游世界
  12. iframe多层嵌套时获取元素
  13. 7z 7zip 日期、时间,文件名
  14. 将硬件规定的通信协议用Lua实现(涉及到很多Lua通信的数据转换)
  15. Qt容器类汇总说明
  16. ListView - SimpleAdapter 行间颜色交替(转)
  17. git设置忽略文件和目录
  18. mysql返回字符串在另外一个字符串中第n次出现的方法。
  19. 接口规范,js处理json,php返回给ajax的数据格式
  20. Web Worker 案例

热门文章

  1. ABP框架踩坑记录
  2. PHPhotos
  3. git install
  4. 大数据技术之_19_Spark学习_01_Spark 基础解析小结(无图片)
  5. python学习笔记05-列表
  6. sehll-011:case脚本的基本用法
  7. sql server 2012 数据库日志文件过大,怎么缩小?
  8. python中如何使输出不换行
  9. C# 点击打开浏览器
  10. 0day发布网站[转载]