javaarraylistindexingindexoutofboundsexception

Next in array and index out of bounds


What would be best practice and solution for checking for "Index out of bounds" The following solution works but feels quite hacky. Is there any better alternatives?

public void nextPerson(int index){ //Index is the current location in the arraylist
    try{
        System.out.println(thePeople.get(index++));
    }
    catch (IndexOutOfBoundsException e){
        System.out.println("At the end");
    }
}

Solution

  • I figured out that by having a local variable to keep track of Arraylist index. I was able to instead have 2 methods for handling the moving thoughtout the ArrayList. With one for the current position for outputting.

    if(arrayPosition < thePeople.size() - 1)