所以我试图创建一个方法,将一个arraylist中的所有元素向右移动,最后一个元素将成为第一个元素.当我运行代码时,我被告知我有一个越界错误.这是我到目前为止:
public void shiftRight()
{
//make temp variable to hold last element
int temp = listValues.get(listValues.size()-1);
//make a loop to run through the array list
for(int i = listValues.size()-1; i >= 0; i--)
{
//set the last element to the value of the 2nd to last element
listValues.set(listValues.get(i),listValues.get(i-1));
//set the first element to be the last element
listValues.set(0, temp);
}
}
Run Code Online (Sandbox Code Playgroud)
也许这是你正在进行的练习,但是ArrayList.add(int index,E element)方法几乎可以做到你想要的.
"将指定元素插入此列表中的指定位置.将当前位于该位置的元素(如果有)和任何后续元素移位到右侧(将其添加到索引中)." (斜体添加)
所以只需在列表中的第0位添加最后一个元素.然后从最后删除它.
这里有几个问题:
i > 0否则您将到达想要将元素放在一个位置-1到另一个位置的位置0,从而导致越界错误。listValues.set接受列表中的索引作为第一个参数,您为其提供列表中的对象
public void shiftRight()
{
//make temp variable to hold last element
int temp = listValues.get(listValues.size()-1);
//make a loop to run through the array list
for(int i = listValues.size()-1; i > 0; i--)
{
//set the last element to the value of the 2nd to last element
listValues.set(i,listValues.get(i-1));
}
//set the first element to be the last element
listValues.set(0, temp);
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
11031 次 |
| 最近记录: |