集合类2-TreeSet
来源:互联网 发布:java jar 运行参数 编辑:程序博客网 时间:2024/05/18 10:01
Set集合中的对象不按特定的方式排序,只是简单地把对象加入集合中,但Set中不包含重复对象。由Set接口和Set接口的实现类组成。
TreeSet类不仅实现了Set接口,还实现了java.util.SortedSet接口,因此,TreeSet类实现的Set集合在遍历集合时按照自然顺序递增排序,也可以按照指定比较器递增排序,即可以通过比较器对用TreeSet类实现的Set集合中的对象进行排序。
TreeSet类新增的方法:
first() :返回Set集合中第一个元素
last() :返回Set集合中最后一个元素
comparator():返回此Set中的元素进行排序的比较器。
headSet(E toElement):返回此Set中的toElement之前的所有对象。
subSet(E fromElement,E toElement):返回包含fromElement 到 toElement(不包含)之间的对象。
tailSet(E fromElement):返回包含fromElement 之后的所有对象。
import java.util.*;public class UpdateStu implements Comparable<Object>{//创建类实现Comparable接口 String name; long id; public UpdateStu(String name, long id) {//构造方法 this.id = id; this.name = name; } public int compareTo(Object o) { //参照代码说明 UpdateStu upstu = (UpdateStu) o; int result = id > upstu.id ? 1 : (id == upstu.id ? 0 : -1); return result; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static void main(String[] args) { UpdateStu stu1 = new UpdateStu("李同学", 01011); UpdateStu stu2 = new UpdateStu("陈同学", 01021); UpdateStu stu3 = new UpdateStu("王同学", 01051); UpdateStu stu4 = new UpdateStu("马同学", 01012); TreeSet<UpdateStu> tree = new TreeSet<>(); tree.add(stu1); tree.add(stu2); tree.add(stu3); tree.add(stu4); Iterator<UpdateStu> it = tree.iterator(); System.out.println("Set集合中的所有元素:"); while (it.hasNext()) { UpdateStu stu = (UpdateStu) it.next(); System.out.println(stu.getId() + " " + stu.getName()); } it = tree.headSet(stu2).iterator();//截取排在stu2前面的对象 System.out.println("截取前面部分的集合:"); while (it.hasNext()) { UpdateStu stu = (UpdateStu) it.next(); System.out.println(stu.getId() + " " + stu.getName()); } it = tree.subSet(stu2, stu3).iterator();//截取排在stu2与stu3之间的对象 System.out.println("截取中间部分的集合"); while (it.hasNext()) { UpdateStu stu = (UpdateStu) it.next(); System.out.println(stu.getId() + " " + stu.getName()); } } }
存入TreeSet类实现的Set集合必须实现Comparable接口,该接口中的compareTo(Object o)方法比较此对象与指定对象的排序。如果该对象小于、等于或大于指定对象,则分别返回负整数、0或正整数。
0 0
- 集合类2-TreeSet
- 【集合】TreeSet类
- JAVA 集合类 TREESET
- 集合类的学习--TreeSet
- Java 集合学习<2>TreeSet
- 集合(2)TreeSet , 泛型
- 集合之TreeSet(2)
- TreeSet 集合
- TreeSet集合,
- 集合 --- TreeSet
- TreeSet集合
- TreeSet集合
- 集合TreeSet
- TreeSet集合
- TreeSet集合
- TreeSet集合
- 集合-TreeSet
- 20151118 Set集合+HashSet类+TreeSet类
- [BZOJ4373][线段树]算术天才⑨与等差数列
- 简单实现两个listView的联动效果(网络框架Retrofit+Rxjava)
- BZOJ P3437 小P的牧场
- 人工智能终究会抢了我们程序员的饭碗
- Liunx 上面使用Python连接Redis遇到的一些问题
- 集合类2-TreeSet
- Windows BAT脚本中调用BAT脚本导致CMD退出的问题
- 1333: Funny Car Racing(最短路用spfa)
- 20170405_shell编程
- Java中的堆栈
- mybatis 获取 list类型的返回值
- easyUI的目录结构
- 结对编程,四则运算
- C++读入优化