java的HashSet和TreeSet在add()用法的区别。
来源:互联网 发布:人工智能聊天app 编辑:程序博客网 时间:2024/06/06 23:57
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);
}
}
- java的HashSet和TreeSet在add()用法的区别。
- HashSet,TreeSet,LinkedHashSet 的用法和区别
- Java HashSet和TreeSet的区别
- Java中HashSet和TreeSet的区别
- Java中HashSet和TreeSet的区别
- HashSet和TreeSet的区别
- HashSet和TreeSet的区别
- HashSet和TreeSet的区别
- HashSet和TreeSet的区别
- HashSet和TreeSet的区别
- HashSet和TreeSet的区别
- HashSet和TreeSet的区别
- HashSet和TreeSet的区别
- HashSet,和TreeSet的区别
- HashSet 和 TreeSet 的区别
- HashSet和TreeSet的区别
- Java——HashSet和TreeSet的区别
- Java——HashSet和TreeSet的区别
- Android Studio使用gradle-experimental构建NDK工程(无需Android.mk、Application.mk文件)
- Block用法解析
- Unity 对Camera 属性Clear Flags 的SkyBox/Solid Color/Depth Only深度解析
- String类
- 第二章 链路层
- java的HashSet和TreeSet在add()用法的区别。
- hibernate之缓存以及pojo对象的三种状态
- UVALive 7009 Secret Binary Tree(二分查找、dfs)
- 如何用Notepad++运行Python脚本
- 编译Apache问题
- 包装类转化、正则表达式
- laravel5分钟完成登录注册
- hdu 4708 Rotation Lock Puzzle
- 图解Ollydbg简单逆向操作案例