package set;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/*
* TreeSet要求里面的元素是可比较的,才能排序。 否则只能通过比较的类实现Comparable接口或者创建一个比较器对象(Comparator)
*
* HashSet和TreeSet保证不添加重复元素的实现原理的区别:
* HashSet:必须要重写hashCode和equals,先判断hashCode是否相同,再判断是否equals,都相同则认为是相同的对象
* TreeSet:根本不考虑hashCode和equals,要求里面的元素是可比较的,才能排序。
* 否则只能通过比较的类实现Comparable接口或者创建一个比较器对象(Comparator)。
* comparaTo(); 0 compare(); 0
*
* TreeSet set = new TreeSet();
* set.add(xxx);
*
* TreeSet set = new TreeSet(比较器对象);
* set.add(xxx);
*/
//class Dog implements Comparable{
class Dog{
private String name;
private String type;
private int age;
public Dog() {
super();
// TODO Auto-generated constructor stub
}
public Dog(String name, String type, int age) {
super();
this.name = name;
this.type = type;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Dog [name=" + name + ", type=" + type + ", age=" + age + "]";
}
/*@Override
public int compareTo(Object o) {
if(o instanceof Dog)
{
Dog d = (Dog)o;
return this.age-d.age;
}
else
{
return 1;
}
}*/
}
class MyDogComparator implements Comparator<Dog>{
@Override
public int compare(Dog d1, Dog d2) {
// TODO Auto-generated method stub
return d1.getAge()-d2.getAge();
}
}
public class TreeSetDemo2 {
public static void main(String[] args) {
TreeSet set = new TreeSet(new MyDogComparator());
set.add(new Dog("旺财","哈士奇",2));
set.add(new Dog("旺1","哈士奇",4));
set.add(new Dog("旺2","哈士奇",3));
set.add(new Dog("旺3","哈士奇",5));
set.add(new Dog("旺4","小野狗",3));
set.add(new Dog("旺财","藏獒",2));
set.add(new Dog("旺财","哈士奇",2));
set.add(new Dog("旺2","哈士奇",3));
Iterator it = set.iterator();
// set.Dog cannot be cast to java.lang.Comparable
//两种方法 1.Dog类实现Comparable接口 2.写一个比较器
while(it.hasNext())
{
System.out.println(it.next());
}
}
}