我必须创建一个程序来查找人员列表中的 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));
}
提前致谢
最佳答案
检查循环
for (int i = 2; i < persons.size(); i++) {
Cdates = Cdates.intersection(persons.get(i).getDateSet());
}
您的 for
循环变量 i
从初始值 2 开始,并且它正在递增,而它应该递减,对吗?
关于java - 越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46539780/