如何在java中将Arraylist中的元素移到右边

Cod*_*irl 2 java arraylist

所以我试图创建一个方法,将一个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)

use*_*300 7

也许这是你正在进行的练习,但是ArrayList.add(int index,E element)方法几乎可以做到你想要的.

"将指定元素插入此列表中的指定位置.将当前位于该位置的元素(如果有)和任何后续元素移位到右侧(将其添加到索引中)." (斜体添加)

所以只需在列表中的第0位添加最后一个元素.然后从最后删除它.


use*_*281 4

这里有几个问题:

  1. 您的 for 循环条件需要排除第零个元素,因此应该如此,i > 0否则您将到达想要将元素放在一个位置-1到另一个位置的位置0,从而导致越界错误。
  2. 将第一个元素设置为最后一个元素应该在循环之外。
  3. 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)