1

I have an ArrayList, bag, that stores objects of type Bean, a class that contains the color of a Bean, as stored in a boolean. If I want to retrieve the last Bean in the bag to check what color it is, how would I do that?

if (((Bean)bag.get(bag.size())).getColor() == true)
   blackCounter++;
else
   whiteCounter++;

Here, I am trying to check to see if the last Bean in the bag is either black or white, and then adding to a counter that stores the total number of Beans of each color currently in the bag. However, I get an OutOfBounds exception at index 1 every time I run it. How could I fix this? (PS: We just learned ArrayLists in my CS class this week, so I am still not 100% on the concept, although I think I am starting to grasp it.)

EDIT: The size of this bag changes drastically, and is sometimes 0. However, BlueJ says that I get the error when the size is 1, as is the index I am trying to access.

Original problem solved. Follow-up question: When I run the program, everything will work, but it will sometimes give me an out of bounds exception with the following snippet as well, and since the program has to execute 50 different times for my assignment, that is problematic.

while (bag.size() > 1)
{
    int grab1 = rn.nextInt(bag.size());
    int grab2 = rn.nextInt(bag.size());

    boolean place1 = bag.get(grab1).getColor();
    boolean place2 = bag.get(grab2).getColor();

    if (place1 && place2)
    {
        bag.remove(grab2);
    }

    if (place1 && !place2)
    {
        bag.remove(grab1);
    }

    if (!place1 && place2)
    {
        bag.remove(grab2);
    }

    if(!place1 && !place2)
    {
        bag.remove(grab1);
        bag.remove(grab2); //This line will give me an Out of Bounds Exception when the size and the index are the same
        bag.add(new Bean());
    }
}

I tried adding -1s here as well, but then it will occasionally give me out of bounds exceptions for the index -1.

resueman
  • 10,572
  • 10
  • 31
  • 45
nccows
  • 107
  • 1
  • 2
  • 10

4 Answers4

1

Try this:

public Bean getLastElement(List<Bean> myList) {
    return myList.get(myList.size() - 1);
}
blalasaadri
  • 5,990
  • 5
  • 38
  • 58
1

The index counting starts at 0 ,so if array.size() returns 5 ,4 is the last item.

((Bean)bag.get(bag.size()-1))
SteveL
  • 3,331
  • 4
  • 32
  • 57
1

Collections have 0-based indexing, so the last element is size - 1. You'll need to add a guard for when your collection is empty.

Guillaume
  • 18,494
  • 8
  • 53
  • 74
1

You need to invoke getSize() - 1, as the List is 0-indexed.

For instance, the first index in a 5-sized List is 0, and the last index is 4.

You should also check that the list is not empty before attempting that, by invoking isEmpty().

Example

// assuming getColor weirdly returns boolean
if (bag != null && !bag.isEmpty() && ((Bean)bag.get(bag.size() - 1)).getColor()) {
   blackCounter++;
}
else {
   whiteCounter++;
}
Mena
  • 47,782
  • 11
  • 87
  • 106