我必须创建一个程序,该程序将在人员列表中找到commonDates。
public DateSet commonDates() {
if (persons.size() >= 2) {
DateSet Cdates =
persons.get(0).getDateSet().intersection(persons.get(1).getDateSet());
for (int i = 2; i < persons.size(); i++) {
Cdates = Cdates.intersection(persons.get(i).getDateSet());
}
return Cdates;
}
else {
throw new IllegalArgumentException();
}
}
以下是相交方法:
public DateSet intersection(DateSet other) {
DateSet dates2 = (DateSet) other;
DateSet NewDateSet = new DateSet();
for(int i = 0; i < dates.size(); i++) {
if (dates.get(i).equals(dates2.dates.get(i))) {
NewDateSet.add(dates.get(i));
}
}
return NewDateSet;
}
commonDates的Junit测试如下所示
@Test
public void testCommonDates() {
DatePicker persons = new DatePicker();
List<Date> dates = new ArrayList<Date>();
Person P1 = new Person("Joop");
Person P2 = new Person("Joopie");
Person P3 = new Person("Jaapie");
Date D1 = new Date("maandag");
Date D2 = new Date("dinsdag");
dates.add(D1);
persons.addPerson(P1);
persons.addPerson(P2);
P1.add(D1);
P2.add(D1);
P3.add(D1);
P1.add(D2);
assertThat("commonDates should return dates all persons have in common", persons.commonDates(), equalTo(dates));
}
以下是我收到的错误消息
提前感谢
发布于 2017-10-03 16:14:33
检查循环
for (int i = 2; i < persons.size(); i++) {
Cdates = Cdates.intersection(persons.get(i).getDateSet());
}
您的for
-loop变量i
从初始值2开始,它是递增的,而它应该是递减的,对吗?
发布于 2017-10-03 16:55:27
我建议为public DateSet intersection(DateSet other)
方法创建一个单独的测试,因为这是您的问题所在。看起来有一个问题,因为它要求集合的长度相同。
您可能应该使用像这样的东西
Set<Date> intersection = new HashSet<>(dates1);
intersection.retainAll(dates2);
而不是使用自定义数据类型。
https://stackoverflow.com/questions/46539780
复制相似问题