TreeSet的简单使用
2015-08-03 11:23
218 查看
仅仅是使用方法,非源码分析。
输出:
Ald
Boo
CC
Se
使用TreeSet集合时,元素必须实现Comparable接口。
测试类:
输出结果:
name:tom age:12
name:shldom age:23
name:woa age:45
name:moe age:87
public class Test { public static void main(String[] args) { TreeSet<String> treeSet=new TreeSet<>(); treeSet.add("Se"); treeSet.add("Ald"); treeSet.add("Boo"); treeSet.add("CC"); Iterator<String> iterator=treeSet.iterator(); while (iterator.hasNext()) { String string = (String) iterator.next(); System.out.println(string); } } }
输出:
Ald
Boo
CC
Se
使用TreeSet集合时,元素必须实现Comparable接口。
public class Person implements Comparable<Person> { private String name; private int age; public Person() { // TODO Auto-generated constructor stub } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { // TODO Auto-generated method stub return "name:" + getName() + " age:" + getAge(); } /** * 升序排列 */ @Override public int compareTo(Person person) { // TODO Auto-generated method stub if (this.getAge() > person.getAge()) { return 1; } else if (this.getAge() == person.getAge()) { return 0; } else { return -1; } } }
测试类:
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub TreeSet<Person> tSet = new TreeSet<>(); tSet.add(new Person("shldom", 23)); tSet.add(new Person("tom", 12)); tSet.add(new Person("woa", 45)); tSet.add(new Person("moe", 87)); Iterator<Person> iterator=tSet.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } } }
输出结果:
name:tom age:12
name:shldom age:23
name:woa age:45
name:moe age:87
相关文章推荐
- Web.config中设置启用webservice远程调试访问
- CSS学习笔记
- redis安装
- 谁登录了你的linux
- java中repaint()定时刷面板问题及演示代码(附滚动条实现)
- 数据库设计中,多对多关系使用使用逗号分割关联讨论
- C语言中的const关键字
- Python中的字符串
- IOS得到所选择的背景图片的坐标颜色
- android samsung note3 device not found
- C#创建一个polygon类
- react-native试玩(2)
- RMB转换人民币大小金额
- hdu5200 Trees(逆向思维+离线处理)
- 读文件封装类
- 锦上
- Window10 安装问题汇总
- 官方摇杆使用
- 杭电 1312 Red and Black 递归 附翻译
- 最小费用最大流---MCMF模版