HashSet和TreeSet实现的不同

HashSet 

 集合判断两个元素相等的标准是两个对象通过equals方法比较相等
TreeSet类 自然排序使用要排序元素的CompareTo(Objectobj)方法来比较元素之间大小关系,然后将元素按照升序排列。

java.util.Date uDate = new java.util.Date(time);
java.sql.Timestamp timestamp = new java.sql.Timestamp(time);

Set hSet = new HashSet();
Set tSet = new TreeSet();
hSet.add(uDate);
hSet.add(timestamp);
tSet.add(uDate);
tSet.add(timestamp);
System.out.println(hSet.toString());
System.out.println(tSet.toString());

hSet = new HashSet();
tSet = new TreeSet();
hSet.add(timestamp);
hSet.add(uDate);
tSet.add(timestamp);
tSet.add(uDate);
System.out.println(hSet.toString());
System.out.println(tSet.toString());

输入结果如下:
原因: 1 add方法调用后加入对象的方法
          2 TimeStamp.equals(Date) = false
             TimeStamp.compareTo(Date) = 0
          3 Date.equals(TimeStamp.) = true  
             Date.compareTo(TimeStamp) = 1

[Wed Mar 23 09:50:29 CST 2016, 2016-03-23 09:50:29.952]
[Wed Mar 23 09:50:29 CST 2016]
[2016-03-23 09:50:29.952]
[2016-03-23 09:50:29.952, Wed Mar 23 09:50:29 CST 2016]
posted on 2017-02-14 10:59  sdfczyx  阅读(124)  评论(0编辑  收藏  举报