我正在尝试编写一个方法,将其执行的relationship
对象的Lord
元素增加10,并将ArrayList中每个其他对象的相同元素增加3我的代码导致循环迭代6次,它只应迭代2次。谁能看到可能导致这种行为的原因?下面是相关的代码和堆栈跟踪线:
MainTest.java
public class MainTest {
private ArrayList<Lord> baratheons;
private ArrayList<Lord> starks;
//Setup & Teardown
@BeforeEach
public void setUp() throws Exception {
baratheons = new ArrayList<Lord>();
baratheons.add( new Lord("Robert", 15));
baratheons.add( new Lord("Renly", -5));
baratheons.add( new Lord("Stannis", 30));
starks = new ArrayList<Lord>();
starks.add( new Lord("Robb", -60));
starks.add( new Lord("Eddard", 0));
starks.add( new Lord("Jon", 90));
}
@AfterEach
public void tearDown() throws Exception {
baratheons = null;
}
//tests
@Test
public void testGratefulLord() {
int x = baratheons.get(0).getRelationship();
baratheons.get(0).giveFief(baratheons, baratheons.get(0));
assertEquals(baratheons.get(0).getRelationship(), (x+=10));
}
@Test
public void testAlliesApprove() {
int x = starks.get(0).getRelationship();
starks.get(0).giveFief(starks, starks.get(0));
assertEquals(starks.get(1).getRelationship(), x+3);
}
Lord.java
public void giveFief(ArrayList<Lord> arrayListLord, Lord lordGivenFief) {
lordGivenFief.relationship += 10;
ArrayList<Lord> temp = new ArrayList<Lord>();
temp.add(lordGivenFief);
arrayListLord.remove(lordGivenFief);
ArrayList<Lord> alliesArrayList = new ArrayList<Lord>(arrayListLord);
for (int i = 0; i<(alliesArrayList.size()); i++) {
alliesArrayList.get(i).setRelationship(relationship+=3);
System.out.printf("I have iterated! The current index is %d \n", i);
}
}
堆栈跟踪
java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at mainPackage.Lord.giveFief(Lord.java:28)
at mainPackage.MainTest.testGratefulLord(MainTest.java:40)
编辑:AssertionFailedError跟踪
testGratefulLord()
org.opentest4j.AssertionFailedError:expected:&lt; 28&gt;但是:&lt; 25&gt;
testAlliesApprove()
org.opentest4j.AssertionFailedError:expected:&lt; -44&gt;但是:&lt; -57&gt;