user1078028
user1078028

Reputation: 5

IndexOutOfBoundsException ArrayList Error

I'm writing a basic java card game but I'm getting a java.lang.IndexOutOfBoundsException: Index: 6, Size 6 (in java.util.ArrayList error on this bit of code, could you help me please?

 public void simple() { 
        if (cards.get(cards.size()-1).getSuit().equals(cards.get(cards.size()).getSuit())) { 

            int last=cards.size()-1;
            Card c=cards.remove(last);
            cards.set(last-1,c);

        }
        else {
            System.out.println("hi");
        }
    }

Upvotes: 0

Views: 664

Answers (3)

Nate W.
Nate W.

Reputation: 9249

Here's your problem: cards.get(cards.size())

An ArrayList is just like an array - if it has 6 elements in it, then the index of the last item is 5 (since arrays start at index 0, not 1).

Upvotes: 0

Jack Edmonds
Jack Edmonds

Reputation: 33171

Your problem occurs on your second line with the code cards.get(cards.size()).

Indices for lists in Java start at 0 so cards.size() would, by definition, be accessing an element outside the cards collection and throwing the IndexOutOfBoundsException. The last element in cards will always be atcards.size()-1`.

Upvotes: 0

corsiKa
corsiKa

Reputation: 82559

Calling cards.get(cards.size()) will fail every time.

This is because they're 0 indexed. So if you have size 6, your indexes are 0,1,2,3,4,5.

If you want the last two cards, use cards.get(cards.size()-2) and cards.get(cards.size()-1).

Upvotes: 7

Related Questions