1、TreeSet:数据元素可以排序且不可重复
Set接口:HashSet,元素必须重写hashcode和equasls方法。
去重:比较等于0即重复
1、元素可以排序 java.lang.Comparable + compareTo
new TreeSet()
2、排序业务类 java.util.Comparator + compare
new TreeSet(Comparator
2、解决数据重复问题
Person.java
package junit.matrix.col;
public class Person {
// 名称,设置final是为了不允许再修改数据
private final String name;
// 帅气指数,设置final是为了不允许再修改数据
private final int handsome;
public Person() {
name = null;
handsome = 0;
}
public Person(String name, int handsome) {
super();
this.name = name;
this.handsome = handsome;
}
public String getName() {
return name;
}
public int getHandsome() {
return handsome;
}
@Override
public String toString() {
return "姓名:" + this.name + ",帅气指数:" + this.handsome + "\n";
}
}
TreeSetDemo.java
package junit.matrix.col;
import java.util.TreeSet;
/**
* 提供了解耦的方式:业务排序类
*
* TreeSetDemo<BR>
* 创建人:Matrix <BR>
* 时间:2016年2月24日-下午5:13:09 <BR>
* @version 1.0.0
*
*/
public class TreeSetDemo {
public static void main(String[] args) {
Person p1 = new Person("matrix", 100);
Person p2 = new Person("ada", 1000);
Person p3 = new Person("keke", 3000);
// 依次存放到TreeSet容器中,使用排序的业务类(匿名内部类)
TreeSet<Person> persons = new TreeSet<Person>(new java.util.Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
// 升序
return o1.getHandsome() - o2.getHandsome();
}
});
// TreeSet在添加数据时排序
persons.add(p1);
persons.add(p2);
persons.add(p3);
System.out.println(persons);
// 不能改变数据
// p3.setHandsome(100);
// p3.setName("Array");
// System.out.println(persons);
}
}
3、
Worker.java
package junit.matrix.col;
public class Worker implements java.lang.Comparable<Worker> {
// 工种
private String type;
// 工资
private double salary;
public Worker() {
}
public Worker(String type, double salary) {
super();
this.type = type;
this.salary = salary;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
// 按照工资升序
@Override
public int compareTo(Worker o) {
return this.salary > o.salary ? 1 : (this.salary == o.salary ? 0 : -1);
}
@Override
public String toString() {
return "工种:" + this.type + ",工资:" + this.salary + "\n";
}
}
TreeSetDemo02.java
package junit.matrix.col;
import java.util.TreeSet;
/**
* 实体类实现Comparable接口的应用
*
* TreeSetDemo02<BR>
* 创建人:Matrix <BR>
* 时间:2016年2月24日-下午5:12:58 <BR>
* @version 1.0.0
*
*/
public class TreeSetDemo02 {
public static void main(String[] args) {
Worker w1 = new Worker("垃圾回收员", 12000);
Worker w2 = new Worker("农民工", 8000);
Worker w3 = new Worker("程序员", 5000);
TreeSet<Worker> employee = new TreeSet<Worker>();
employee.add(w1);
employee.add(w2);
employee.add(w3);
System.out.println(employee);
}
}
运行结果
[工种:程序员,工资:5000.0
, 工种:农民工,工资:8000.0
, 工种:垃圾回收员,工资:12000.0
]