[英]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? 我正在编写一个基本的Java纸牌游戏,但是却遇到了java.lang.IndexOutOfBoundsException: Index: 6, Size 6 (in java.util.ArrayList
此代码段java.lang.IndexOutOfBoundsException: Index: 6, Size 6 (in java.util.ArrayList
错误,您能帮我吗?
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. cards.get(cards.size())
调用cards.get(cards.size())
都会失败。
This is because they're 0 indexed. 这是因为它们被索引为0。 So if you have size 6, your indexes are 0,1,2,3,4,5
. 因此,如果大小为6,则索引为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)
. 如果要最后两张卡,请使用cards.get(cards.size()-2)
和cards.get(cards.size()-1)
。
Your problem occurs on your second line with the code cards.get(cards.size())
. 您的问题出现在第二行,代码为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
. Java中列表的索引从0开始,因此,根据定义, cards.size()
将访问cards
集合之外的元素并抛出IndexOutOfBoundsException
。 The last element in cards will always be at
cards.size()-1`. cards will always be at
的最后一个元素cards will always be at
cards.size()-1`。
Here's your problem: cards.get(cards.size())
这是您的问题: 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). ArrayList
就像一个数组-如果其中有6个元素,则最后一项的索引为5(因为数组从索引0开始,而不是1)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.