0

I'm trying to write a method that will increase the relationship element of the Lord object it is performed on by 10, and increase the same element of every other object in the ArrayList by 3. The code I have causes the loop to iterate 6 times when it should only iterate 2 times. Can anyone see what might be causing this behaviour? Below is the relevant code and stack trace lines:

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);
    }
}

Stack Trace

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)

EDIT: AssertionFailedError Traces

testGratefulLord()

org.opentest4j.AssertionFailedError: expected: <28> but was: <25>

testAlliesApprove()

org.opentest4j.AssertionFailedError: expected: <-44> but was: <-57>

Eamon Cullen
  • 65
  • 1
  • 1
  • 7

0 Answers0