TreeSet底层数据结构是二叉树
判断对象是否一致是通过是对象自身有比较的方法,即使类实现Comparable接口,重写compareTo方法,自己定义比较规则,
若是不想用元素本身的比较方法,又不想修改代码,那么可以使集合自身具有比较的方法,就是在集合初始化时实现Comparator接口,即Set s =new TreeSet(new Mycomparetor implements Comparator).
比较过程优先使用comparator比较器。
/*
元素自身有比较性
*/
public class TreeSetTest {
public static void main(String[] args) {
Set s = new TreeSet();
s.add(new Person4("lisi",23));
s.add(new Person4("liiisi",20));
s.add(new Person4("lisi",21));
s.add(new Person4("wangwu",20));
// s.add(12);
System.out.println(s);
Iterator it = s.iterator();
while(it.hasNext()){
Person4 p1 =(Person4)it.next();
System.out.println(p1.getName()+"----"+p1.getAge());
}
}
}
class Person4 implements Comparable{
private String name;
private int 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 Person4(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public int compareTo(Object o) {
if(!(o instanceof Person4)){
throw new RuntimeException("不是person对象");
}
Person4 p = (Person4)o;
System.out.println(this.name+"-----compareTo----"+p.name);
if(this.age==p.age){
return this.name.compareTo(p.name);
}
else
return new Integer(this.age).compareTo(new Integer(p.age));
}
}
/*
使用comparetor比较器
*/
public class TreeSetTest {
public static void main(String[] args) {
Set s = new TreeSet(new Mycomparator());
s.add(new Person4("lisi",23));
s.add(new Person4("liiisi",20));
s.add(new Person4("lisi",23));
s.add(new Person4("wangwu",20));
// s.add(12);
System.out.println(s);
Iterator it = s.iterator();
while(it.hasNext()){
Person4 p1 =(Person4)it.next();
System.out.println(p1.getName()+"----"+p1.getAge());
}
}
}
class Person4 {
private String name;
private int 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 Person4(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
class Mycomparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
if(!(o1 instanceof Person4)||!(o2 instanceof Person4))
throw new RuntimeException("比较对象中有不是Person4的元素");
Person4 p1 =(Person4)o1;
Person4 p2 =(Person4)o2;
System.out.println(p1.getName()+"---调用comparator--"+p2.getName());
if(p1.getAge()==p2.getAge())
return p1.getName().compareTo(p2.getName());
else
return p1.getAge()-p2.getAge();
}
}