TreeSet之定制排序和自然排序
TreeSet的几大特点:
1、TreeSet中存储的类型必须是一致的,不能一下存int,一下又存string
2、TreeSet在遍历集合元素时,是有顺序的【从小到大】(我的理解,如果存的字母,按字典序排列)
3、排序:当向TreeSet中添加自定义对象时,有2种排序方法,1:自然排序 2、定制排序
自然排序:要求自定义类实现java.lang.Comparable接口并重写compareTo(Object obj)方法。在此方法中,指明按照自定义类的哪个属性进行排序 一、自然排序示例:
1、定义一个类(文章中为Employee)实现Comparable接口
2、重写Comparable接口中的compareTo()方法
3、在compareTo()中按指定属性进行排序(文章按name进行排序)
代码示例:
Employee类
public class Employee implements Comparable{
public int compareTo(Object o) {
if (o instanceof Employee) {
Employee e = (Employee) o;
return this.name.compareTo(e.name);
}
return 0;
}
private String name;
private int age;
private MyDate birthday;
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 MyDate getBirthday() {
return birthday;
}
public void setBirthday(MyDate birthday) {
this.birthday = birthday;
}
public Employee(String name, int age, MyDate birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
if (age != employee.age) return false;
if (name != null ? !name.equals(employee.name) : employee.name != null) return false;
return birthday != null ? birthday.equals(employee.birthday) : employee.birthday == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
return result;
}
}
测试类
public class TreeSetTest {
public static void main(String[] args) {
test1();
}
/**
* 自然排序 按name排序 所以你的Employee必须实现Comparable接口
*/
public static void test1() {
Employee e1 = new Employee("liudehua",55,new MyDate(4,12,1997));
Employee e2 = new Employee("11",55,new MyDate(5,12,1997));
Employee e3 = new Employee("22",55,new MyDate(6,12,1997));
Employee e4 = new Employee("33",55,new MyDate(7,12,1997));
Employee e5 = new Employee("44",55,new MyDate(8,12,1997));
TreeSet set = new TreeSet();
set.add(e1);
set.add(e2);
set.add(e3);
set.add(e4);
set.add(e5);
Iterator i = set.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
输出结果按name进行排序。按照汉语拼音的顺序
二、定制排序示例
Employee1 类
public class Employee1 {
private String name;
private int age;
private MyDate birthday; 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 MyDate getBirthday() {
return birthday;
} public void setBirthday(MyDate birthday) {
this.birthday = birthday;
} public Employee1(String name, int age, MyDate birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
} @Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
} @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; Employee1 employee = (Employee1) o; if (age != employee.age) return false;
if (name != null ? !name.equals(employee.name) : employee.name != null) return false;
return birthday != null ? birthday.equals(employee.birthday) : employee.birthday == null;
} @Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
return result;
}
}
MyDate类
public class MyDate {
private int day;
private int month;
private int year;
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public MyDate(int day, int month, int year) {
this.day = day;
this.month = month;
this.year = year;
}
@Override
public String toString() {
return "MyDate{" +
"day=" + day +
", month=" + month +
", year=" + year +
'}';
}
//先重写MyDate的equals()和hashCode()方法,在重写Employee中的
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyDate myDate = (MyDate) o;
if (day != myDate.day) return false;
if (month != myDate.month) return false;
return year == myDate.year;
}
@Override
public int hashCode() {
int result = day;
result = 31 * result + month;
result = 31 * result + year;
return result;
}
}
测试类
public class TreeSetTest1 {
public static void main(String[] args) {
test2();
}
/**
* 定制排序 按指定生日来排
*/
public static void test2() {
Comparator comparator = new Comparator() {
public int compare(Object o1, Object o2) {
if (o1 instanceof Employee1 && o2 instanceof Employee1) {
Employee1 e1 = (Employee1)o1;
Employee1 e2 = (Employee1)o2;
MyDate birth1 = e1.getBirthday();
MyDate birth2 = e2.getBirthday();
if(birth1.getYear() != birth2.getYear()) {
//定义的类型是 int 所以使用“-”减号代替compareTo()
return birth1.getYear() - birth2.getYear();
} else {
if (birth1.getMonth() != birth2.getMonth()) {
return birth1.getMonth() - birth2.getMonth();
} else {
return birth1.getDay() - birth2.getDay();
}
}
}
return 0;
}
};
// “一定要指明按特定对象进行比较 comparator参数一定要加”
TreeSet set = new TreeSet(comparator);
Employee1 e1 = new Employee1("liudehua",55,new MyDate(5,8,1990));
Employee1 e2 = new Employee1("11",55,new MyDate(5,11,1997));
Employee1 e3 = new Employee1("22",55,new MyDate(6,10,1997));
Employee1 e4 = new Employee1("33",55,new MyDate(7,9,1997));
Employee1 e5 = new Employee1("44",55,new MyDate(8,8,1997));
set.add(e1);
set.add(e2);
set.add(e3);
set.add(e4);
set.add(e5);
Iterator i = set.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
总结:
自然排序实现的是comparable接口。其在类可以修改时使用。 定制排序实现的是comparator接口。其在类不可以修改时使用 在使用定制排序或是自然排序时,在其用到的类中都要重写hashCode()与equals()方法 comparable和comparator的区别:[参考博文:http://blog.csdn.net/excellentyuxiao/article/details/52344594]
Comparator在util包下,Comparable在lang包下。java中的对象排序都是以comparable接口为标准的。comparator是在对象外部实现排序。
TreeSet之定制排序和自然排序的更多相关文章
- TreeMap定制排序和自然排序
TreeMap定制排序和自然排序自然排序是实现Comparable接口的方法.代码如下: @Override public int compareTo(Object o) { if (o instan ...
- Java基础知识强化之集合框架笔记44:Set集合之TreeSet保证元素唯一性和自然排序的原理和图解
1. TreeSet保证元素唯一性和自然排序的原理和图解 2. TreeSet唯一性以及有序性底层剖析: 通过观察TreeSet的add()方法,我们知道最终要看TreeMap的put()方法. 跟踪 ...
- java TreeSet的排序之自然排序
TreeSet会调用元素的compareTo(Object o)方法来比较元素之间的大小关系,然后将集合里的元素按升序排列.此时需要排序元素的类必须实现Compareble接口,并覆写其int com ...
- Java基础 TreeSet()来实现数组的【定制排序】 : Comparable接口(自然排序) 或者 Comparator接口 (定制排序)
笔记: //排序真麻烦!没有C++里的好用又方便!ORZ!ORZ!数组排序还还自己写个TreeSet()和( Comparable接口(自然排序) 或者 Comparator接口 (定制排序))imp ...
- Java基础知识强化之集合框架笔记46:Set集合之TreeSet存储自定义对象并遍历练习2(自然排序:Comparable)
1. TreeSet存储自定义对象并遍历练习2: (1)Student.java package cn.itcast_06; /* * 如果一个类的元素要想能够进行自然排序,就必须实现自然排序接口 * ...
- Java基础知识强化之集合框架笔记45:Set集合之TreeSet存储自定义对象并遍历练习1(自然排序:Comparable)
1. 自然排序: TreeSet会调用集合元素的compareTo(Object obj)方法来比较元素之间的大小关系,然后将集合元素按照升序排列,这种方式就是自然排序. Java中提供了一个Comp ...
- TreeSet集合排序方式一:自然排序Comparable
TreeSet集合默认会进行排序.因此必须有排序,如果没有就会报类型转换异常. 自然排序 Person class->实现Comparable,实现compareTo()方法 package H ...
- 《java入门第一季》之集合框架TreeSet存储元素自然排序以及图解
这一篇对TreeSet做介绍,先看一个简单的例子: * TreeSet:能够对元素按照某种规则进行排序. * 排序有两种方式 * A:自然排序: 从小到大排序 * B:比较器排序 Comp ...
- TreeSet集合的自然排序与比较器排序、Comparable接口的compareTo()方法
[自然排序] package com.hxl; public class Student implements Comparable<Student> { private String n ...
随机推荐
- 【uoj#207】共价大爷游长沙 随机化+LCT维护子树信息
题目描述 给出一棵树和一个点对集合S,多次改变这棵树的形态.在集合中加入或删除点对,或询问集合内的每组点对之间的路径是否都经过某条给定边. 输入 输入的第一行包含一个整数 id,表示测试数据编号,如第 ...
- Oracle 同名字段的该行数据按照创建时间最新的隐藏其他
1.需求,表 SYS_INFO 的 NAME 字段会重复,按照 创建时间CREATE_AT 字段,取最新一条,其他隐藏 SELECT * FROM (SELECT T.*,ROW_NUMBER ...
- 【BZOJ4200】【NOI2015】小园丁与老司机(动态规划,网络流)
[BZOJ4200][NOI2015]小园丁与老司机(动态规划,网络流) 题面 BZOJ权限题,洛谷链接 题解 一道二合一的题目 考虑第一问. 先考虑如何计算六个方向上的第一个点. 左右上很好考虑,只 ...
- 【BZOJ2437】【NOI2011】兔兔与蛋蛋(博弈论,二分图匹配)
[BZOJ2437][NOI2011]兔兔与蛋蛋(博弈论,二分图匹配) 题面 BZOJ 题解 考虑一下暴力吧. 对于每个状态,无非就是要考虑它是否是必胜状态 这个直接用\(dfs\)爆搜即可. 这样子 ...
- 特征点检测学习_2(surf算法)
依旧转载自作者:tornadomeet 出处:http://www.cnblogs.com/tornadomeet 特征点检测学习_2(surf算法) 在上篇博客特征点检测学习_1(sift算法) 中 ...
- Codeforces 937.D Sleepy Game
D. Sleepy Game time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...
- UVA-10791 数学
UVA-10791 题意: 输入n (1<=n<2^31) 求至少两个正整数使得他们的lcm等于n并且他们的和最小,输出最小和 代码: // a*b=lcm*gcd => a=lcm ...
- 替换换行符:回车换行CR/LF
windows采用回车+换行CR/LF表示下一行,UNIX/Linux使用换行符LF表示下一行,MAC OS系统使用用回车符CR表示下一行. CR使用符号'\r'表示, ASCII码是13: LF使用 ...
- mysql 查询小demo
两张表的的结构如下,需求是写出从one表到two表和从two表到one表的查询转换. create table student_one( name varchar(50) default '' not ...
- NOIP 2015 提高组 Day1
期望得分:100+100+100=300 实际得分:100+100+45=245 T3 相似的代码 复制过去 没有改全,痛失55分 http://www.cogs.pro/cogs/page/page ...