0

// this this the orginal code:

public void searchBird (int indexPosition) {
    Bird bird = birdList.get(indexPosition);
    System.out.println ("Art:" + bird.getArt ());
    System.out.println ("Location:" + bird.getLocation ());
}

I have so far tried to code a method which returns one element out of the ArrayList with a given index as a parameter. I get an error message when I send in, for example 5, as a parameter.

// and this is what i tried:

public void searchBird (int indexPosition) {
    Bird bird = birdList.get(indexPosition);
    for (int i = 0; i <bird list.size (); i ++) {
        if ((birdList.contains(indexPosition))) {
            System.out.println ("Art:" + bird.getArt ());
            System.out.println ("Location:" + bird.getLocation ());
        }
    }
}

this is what i get;

java.lang.IndexOutOfBoundsException: Index: 5, Size: 3 when calling the method with 5 as a parameter

deHaar
  • 17,687
  • 10
  • 38
  • 51
Kevin Sted
  • 19
  • 9

1 Answers1

0

You are not checking if the given index (indexPosition) is valid in your birdList. If you give an index that is larger than the last index of the list, then you get the IndexOutOfBoundsException you have seen.

Try a little check before calling birdList.get(indexPosition) and skip the entire for loop, you don't need it. Additionally, you should not pass an index to the contains method because it looks for objects, not for indexes (if you have a defined Bird, you can try birdList.contains(bird)).

public void searchBird(int indexPosition) {
    // there might be the following case: indexPosition > maximum index of birdList
    if (indexPosition < birdList.size()) {
        Bird bird = birdList.get(indexPosition);
        System.out.println("Art:" + bird.getArt());
        System.out.println("Location:" + bird.getLocation());
    } else {
        System.out.println("The given index exceeds the list of birds!");
    }
}
deHaar
  • 17,687
  • 10
  • 38
  • 51