简体   繁体   中英

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

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) .

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 at cards.size()-1`.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM