java的HashSet和TreeSet在add()用法的区别。

        TreeSet的方法比HashSet多,多ceilingfloorfirst等。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);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值