Java - 修改ArrayList中每个对象的元素

时间:2018-04-26 14:44:36

标签: java for-loop arraylist

我正在尝试编写一个方法,将其执行的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;

0 个答案:

没有答案