0

我正在调用Arrays.sort(schedule, c);where c 是一个比较器的实例,如下所示:

import java.util.Comparator;

public class FirstOccComparator implements Comparator<AbstractEvent> {

    public int compare(AbstractEvent event1, AbstractEvent event2) {        
          int result = 0;       
          if (event1 == null || event2 == null) {
              //System.out.println("null");
          }
          else if (event1.hasMoreOccurrences() && event2.hasMoreOccurrences()) {
            result = event1.nextOccurrence().compareTo(event2.nextOccurrence());
          }
          return result;
    }

}

我得到的输出不是它应该的。我想知道是否有人可以在这里指出我正确的方向。这是我做过的第一个排序算法,它使用的概念对我来说仍然是新的(比较器和实现),很抱歉关于我的代码的多个问题:)

编辑 这是输出之间的区别:http: //pastebin.com/LWy1jqkt

有两种事件,它们是 hasMoreOccurrence() 和 nextOccurrence() 方法:

每日活动

public boolean hasMoreOccurrences() {
        boolean result = false;
        Date check = nextOccurrence();
        timesCalled--;
        if (check instanceof Date && check != null) {
            result = true;
        }
        return result;
    }

public Date nextOccurrence() {
        if (timesCalled > recurrences) {
            return null;
        }
        else {
            Calendar cal = Calendar.getInstance();
            cal.setTime(startTime);
            cal.add(Calendar.DATE, timesCalled);
            timesCalled++;
            return cal.getTime();
        }
    }

每周活动

public boolean hasMoreOccurrences() {
        Date tmp = nextOccurrence();
        timesCalled--;
        boolean result = false;
        if (tmp instanceof Date && tmp != null) {
            result = true;
        }

        return result;
    }

public Date nextOccurrence() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(startTime);
        cal.add(Calendar.DATE, timesCalled*7);

        if (cal.getTime().compareTo(this.endTime) > 0) {
            return null;
        }
        else {
            timesCalled++;
            return cal.getTime();
        }
    }
4

4 回答 4

2

您的比较器似乎有一些不正确的地方。

例如,如果其中只有一个为空,会发生什么?你希望这些如何排序?现在,如果其中一个为空,则您正在考虑两个相等的事件。

此外,如果一个事件发生的次数更多而另一事件没有发生,会发生什么?现在,如果两个事件都有更多的发生,您只对发生的事件进行比较。您需要处理一个发生而另一个没有发生的情况。

此外,如果出现的是自定义类,您还需要评估该比较器。

于 2011-02-27T18:19:14.210 回答
1

当行为与您的假设不符时,也许是时候检查您的假设了。

“...不是它应该是的...”表明您对 Comparator 应该如何工作的概念与输出不匹配。由于集合中内置的排序算法已被证明,我认为您需要查看您的类及其 Comparator 是否存在错误。

编写一些单元测试,看看你哪里出错了。

如果没有看到结果和您正在分类的课程,就不可能就下一步做什么提供建议。

于 2011-02-27T18:18:27.293 回答
0

问问自己:当 event1 和 event2 不为 null 但其中一个(或两者)已用完时会发生什么?

于 2011-02-27T18:19:17.810 回答
0

您确定平等的算法存在严重缺陷。阅读本文了解更多详情: http: //blogs.msdn.com/b/oldnewthing/archive/2003/10/23/55408.aspx ?wa=wsignin1.0

于 2011-02-27T18:19:44.643 回答