为什么集合不从排序列表中删除重复项?我已按第一行显示的升序对日期进行了排序,但该集合并未删除重复项。这是为什么 ?程序打印:
[Mon Apr 20 12:27:47 CDT 2009, Mon Apr 20 12:27:47 CDT 2009, Sun Dec 20 12:27:47 CST 2009] [Sun Dec 20 12:27:47 CST 2009, 2009 年 4 月 20 日星期一 12:27:47 CDT 2009,4 月 20 日星期一 12:27:47 CDT 2009]
不应该创建一个集合从集合中删除重复的日期吗?
def void testLoadDoc()
{
Date date1 = getCurrentDate(3,20,2009)
Date date2 = getCurrentDate(11,20,2009)
Date date3 = getCurrentDate(3,20,2009)
List<Date> dates = new ArrayList<Date>();
dates.add(date2);
dates.add(date1);
dates.add(date3);
Collections.sort(dates, new CurrencyDateComparator());
Set uniqueDates = new HashSet(dates)
println dates
println uniqueDates
}
private Date getCurrentDate(int month, int day, int year)
{
Calendar cal = Calendar.getInstance();
cal.set(YEAR, year);
cal.set(MONTH, month);
cal.set(DAY_OF_MONTH, day);
return cal.getTime();
}
}
class CurrencyDateComparator implements Comparator
{
/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(Object arg0, Object arg1)
{
Date p = (Date) arg0;
Date q = (Date) arg1;
if (p.before(q))
{
return -1;
}
else if (p.after(q))
{
return 1;
}
else
{
return 0;
}
}
public boolean equals(Object o)
{
if (o instanceof CurrencyDateComparator)
{
CurrencyDateComparator c = (CurrencyDateComparator) o;
return this.equals(o);
}
else
{
return false;
}
}