TreeSet的方法比HashSet多,多ceiling、floor、first等。hashset是无序、不可重复的。treeset是无序、不可重复的、且comparable值不相等的元素。而且treeset按照comparable的顺序进行了排序存储。测试代码如下:
import java.util.*;
public class Test {
public static void main(String[] args) {
//对比TreeSet(无序、不可重复、comparable值不可相同)与HashSet(无序
//,不可重复)在add对象可比较值相等时的区别
TreeSet tree=new TreeSet();
HashSet hash=new HashSet();
Dog dog=new Dog("d0","");
tree.add(dog);//元素不可重复
tree.add(dog);
hash.add(dog);
hash.add(dog);
tree.add(new Dog("d1","shapi"));//元素不可等值
tree.add(new Dog("d4","shap"));
tree.add(new Dog("d3","sha"));
tree.add(new Dog("d2","sh"));
hash.add(new Dog("d1","shapi"));//元素可等值
hash.add(new Dog("d4","shap"));
hash.add(new Dog("d3","sha"));
hash.add(new Dog("d2","sh"));
//第2次录入等值的数据,treeset录入失败
tree.add(new Dog("d1","shapi"));
tree.add(new Dog("d4","shap"));
tree.add(new Dog("d3","sha"));
tree.add(new Dog("d2","sh"));
hash.add(new Dog("d1","shapi"));
hash.add(new Dog("d4","shap"));
hash.add(new Dog("d3","sha"));
hash.add(new Dog("d2","sh"));
System.out.println("tree:");
for(Object obj:tree){
System.out.println(((Dog)obj).toString());
}
System.out.println("hash:");
for(Object obj:hash){
System.out.println(((Dog)obj).toString());
}
}
}
运行结果:
tree:
d0 is dog of
d1 is dog of shapi
d2 is dog of sh
d3 is dog of sha
d4 is dog of shap
hash:
d3 is dog of sha
d2 is dog of sh
d3 is dog of sha
d4 is dog of shap
d1 is dog of shapi
d4 is dog of shap
d0 is dog of
d2 is dog of sh
d1 is dog of shapi
Dog类的代码如下:
public class Dog implements Comparable{
public String type;
public String name;
public Dog(){}
public Dog(String n,String t){
type=t;
name=n;
}
public String toString(){
return this.name+" is dog of "+this.type;
}
public int compareTo(Object obj){
return this.name.compareToIgnoreCase(((Dog)obj).name);
}
}