四、TreeSet
HashSet 是无序的,如果要对集合实现排序,那么就需要使用TreeSet
让TreeSet 实现集合有序有两种方法
一、让元素自身具备比较排序功能,具备比较排序功能的元素只需要实现Comparable 接口。覆盖接口中CompareTo方法
当 TreeSet中元素是基本数据类型时:
package test;import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDemo {
/**
* TreeSet中放置基本类型
* @param args
*/
public static void main(String[] args) {
demo1();
}
//创建类TreeSetDemo的静态方法
public static void demo1() {
TreeSet ts = new TreeSet();
ts.add("abc");
ts.add("zaa");
ts.add("aa");
ts.add("nba");
ts.add("cba");
Iterator it = ts.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
输出结果为:无序,但是这看似无序的集合其中却是有序的,字符串按照字典顺序排序输出。

当 TreeSet中的元素是一个对象时:
package test;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetDemo {
/**
* TreeSet中放置基本类型
* @param args
*/
/*
public static void main(String[] args) {
demo1();
}
//创建类TreeSetDemo的静态方法
public static void demo1() {
TreeSet ts = new TreeSet();
ts.add("abc");
ts.add("zaa");
ts.add("aa");
ts.add("nba");
ts.add("cba");
Iterator it = ts.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}*/
/**
* TreeSet中放置类
* 此时会报错 ,查看错误原因:java.lang.ClassCastException: test.Person cannot be cast to java.lang.Comparable
* 类装换异常
* @param args
*/
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add(new Person("lisi",21));
ts.add(new Person("zhangsan",28));
ts.add(new Person("zhaoliu",25));
ts.add(new Person("zhouqi",29));
ts.add(new Person("wangu",24));
Iterator it = ts.iterator();
while(it.hasNext()){
Person p = (Person)it.next();
System.out.println(p.getName()+":"+p.getAge());
}
}
}
查看结果:Exception in thread "main" java.lang.ClassCastException: test.Person cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at test.TreeSetDemo.main(TreeSetDemo.java:42)原因:TreeSet中存放的自定义类必须实现comparator接口
//自定义类package test;
public class Person{
private String name;
private int age;
//无参构造
public Person() {
super();
}
//带参构造
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
//重写hashCode()方法
@Override
public int hashCode() {
return name.hashCode()+age*27; //将age和name设置成为hashCode。
}
//重写Object的equals() 方法
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(!(obj instanceof Person))
throw new ClassCastException("类型错误");
// System.out.println(this+"....equals....."+obj);
Person p = (Person)obj;
return this.name.equals(p.name) && this.age == p.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;
}
public String toString(){
return name+":"+age;
}
}
让Person类实现Comparable接口,并重写compareTo()方法
package test;
public class Person implements Comparable<Person>{
private String name;
private int age;
//无参构造
public Person() {
super();
}
//带参构造
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
//重写hashCode()方法
@Override
public int hashCode() {
return name.hashCode()+age*27; //将age和name设置成为hashCode。
}
//重写Object的equals() 方法
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(!(obj instanceof Person))
throw new ClassCastException("类型错误");
// System.out.println(this+"....equals....."+obj);
Person p = (Person)obj;
return this.name.equals(p.name) && this.age == p.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;
}
public String toString(){
return name+":"+age;
}
//
@Override
public int compareTo(Person p) {
int temp =this.age-p.age;
return temp==0?this.name.compareTo(p.name):temp;
}
}
此时输出结果就是有序的了

二、让集合自身具备比较功能,定义一个类实现Comparator接口,覆盖compare方法。
四、TreeSet的更多相关文章
- 【java集合框架源码剖析系列】java源码剖析之TreeSet
本博客将从源码的角度带领大家学习TreeSet相关的知识. 一TreeSet类的定义: public class TreeSet<E> extends AbstractSet<E&g ...
- java集合(ArrayList,Vector,LinkedList,HashSet,TreeSet的功能详解)
说起集合,我们会潜意识里想到另外一个与之相近的名词——数组,OK!两者确实有相似之处,但也正是这点才是我们应该注意的地方,下面简单列出了两者的区别(具体功能的不同学习这篇文章后就会明白了): 数组 长 ...
- 对象转型、迭代器Iterator、Set集合、装箱与拆箱、基本数据类型与字符串的转换、TreeSet集合与对象
包的声明与定义 需要注意的是,包的声明只能位于Java源文件的第一行. 在实际程序开发过程中,定义的类都是含有包名的: 如果没有显式地声明package语句,创建的类则处于默认包下: 在实际开发中 ...
- LeetCode第151场周赛(Java)
这是我第一次写周赛的题目,而且还是虚拟的.从这次起,以后就将所有错过的题目都写到博客来.当然既然是我错的,那代码肯定不是我自己的.我会注明来源.并且我会自己敲一遍.多总结总是没坏处的. 另外比较糟糕的 ...
- Java——(四)Collection之Set集合TreeSet类
------Java培训.Android培训.iOS培训..Net培训.期待与您交流! ------- TreeSet类 TreeSet是SortedSet接口的实现类,正如SortedSet名字所暗 ...
- [LeetCode] 4Sum 四数之和
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = tar ...
- Java入门记(四):容器关系的梳理(上)——Collection
目录 一.Collection及子类/接口容器继承关系 二.List 2.1 ArrayList 2.1.1 序列化的探讨 2.1.2 删除元素 2.1.3 调整大小 2.2 Vector和Stack ...
- JAVA基础学习day22--IO流四-对象序列化、管道流、RandomAccessFile、DataStream、ByteArrayStream、转换流的字符编码
一.对象序列化 1.1.对象序列化 被操作的对象需要实现Serializable接口 1.2.对象序列化流ObjectOutputStream与ObjectInputStream ObjectInpu ...
- JAVA基础学习day15--集合二 TreeSet和泛型
一.TreeSet 1.1.TreeSet Set:hashSet:数据结构是哈希表.线程是非同步的. 保证元素唯一性的原理:判断元素的HashCode值是否相同. 如果 ...
随机推荐
- EasyUI动态生成菜单
业务需求:不同角色有不同的权限,我们根据角色加载页面时展示不同的菜单.在easyUI中,菜单一般采用手风琴accordion组件进行展示,一级菜单下可以加载二级菜单,效果如下: 普通用户看到的菜: 管 ...
- iOS中NSTimer的使用
1.初始化 + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelect ...
- PAT 甲级 1056 Mice and Rice (25 分) (队列,读不懂题,读懂了一遍过)
1056 Mice and Rice (25 分) Mice and Rice is the name of a programming contest in which each program ...
- nginx conf 文件
server { listen ; server_name local.light.com; index index.html index.htm index.php; root /home/wwwr ...
- 【leetcode_easy_$】577. Employee Bonus
problem 577. Employee Bonus 参考 1. Leetcode_easy_$_577. Employee Bonus; 2. https://www.cnblogs.com/li ...
- css3 animation 点亮灯光效果
<style> .wrap .bulb { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50% ...
- maven中央仓库的配置在哪里?superpom是什么?中央仓库查找三方包
maven的superpom 每个项目都默认继承的pom 位置 $M2_HOME/lib/maven-model-builder.jar 使用tar -xvf解压后,grep -r central 搜 ...
- Django:django后台传递数据到js中
#奇怪传递字典时前台接收不到???datalist= [{'site': '自强学堂', 'author': '涂伟忠'}]#只要列表能接收# datalist=[[93, 93, 0, 100.01 ...
- 帝国cms 批量替换语句
UPDATE www_92game_net_cnys_ecms_caipu SET titlepic=REPLACE(titlepic,'http://file.92game.net', '') ; ...
- centos 7.2安装git2.x版本
前言 今天在我的centos7.2开发环境安装git2.x时候遇到了各种问题,还好一一解决,为方便大家,这里列出遇到的问题和解决办法,yum默认安装的git1.8版本的,公司git服务器在window ...