HashSet和TreeSet
来源:互联网 发布:广告优化师 编辑:程序博客网 时间:2024/05/16 14:34
HashSet和TreeSet都是Set的实现
HashSet在存放元素时,会获取元素的hashCode()值,通过散列算法找到存放位置。HashSet通过equals()方法比较相等两个对象是否相等
当两个对象的hashCode()值一样,但是equals()返回值为false时会很麻烦,hashCode()值一样HashSet会试图把这两个元素保存在同一个地方,所以会将这两个元素以链表的形式存放在这个位置,因为HashSet访问元素是通过元素的hashCode()值来快速定位的,这种情况会导致HashSet的性能降低
当两个对象的hashCode()返回值不同,equals()返回值为true,则会把相同的元素添加两次,这样就和HashSet的规则(不可重复)冲突了
所以在定义类时重写了equals方法,应该保证当两个对象equals()返回true时,这两个对象的hashCode()返回值也相同
TreeSet:采用红黑树的数据结构来存放元素
TreeSet中的元素是按元素实际值的大小来排序的,TreeSet支持两种排序:自然排序和自定义排序,在默认情况下,采用自然排序
自然排序:TreeSet会调用集合元素的compareTo(Object obj)方法来比较元素之间的大小,然后将元素按升序排列
自定义排序:可以以匿名类的方式重写compare(Object obj1,Object obj2)方法,重新定义比较规则
eg:
Comparator<String> c=new Comparator<String>(){
public int compare(String str1,String str2){
return str2.length()-str1.length();
}
};
- HashSet和TreeSet
- HashSet、LinkedHashSet和TreeSet
- HashSet和TreeSet
- 比较HashSet和TreeSet
- HashSet、TreeSet和LinkedHashSet
- HashSet、LinkedHashSet和TreeSet
- HashSet和TreeSet
- JAVA HashSet和TreeSet
- TreeSet,HashSet和LinkedHashSet
- HashSet和TreeSet
- HashSet和TreeSet
- HashSet,LinkedHashSet和TreeSet
- HashSet和TreeSet用法
- HashSet和TreeSet
- HashSet,TreeSet和LinkedHashSet
- HashSet 和 TreeSet 区别
- TreeSet和HashSet区别
- HashSet和TreeSet
- 运算符重载3
- android 内存优化
- canvas and bitmap 比较不错的文章分享下
- python中的reduce介绍:
- ProjectOne(04) - 番外篇02 requirejs初体验
- HashSet和TreeSet
- 1041. 考试座位号
- Activity绑定自定义视图
- HDU 1017 A Mathematical Curiosity
- [Usaco2015 FEB Gold][2016-2-21]考试总结
- Learn Unity - Scripts(中级教程)
- sgu499
- 飞思卡尔智能车摄像头矫正方案
- iOS的主要框架介绍