如何在Java中将ArrayList中的元素向右移动

5

我正在尝试创建一个方法,将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); 
    }

}

这个可能会对你有所帮助:https://dev59.com/YmrWa4cB1Zd3GeqP8TVL - Ramiz Wachtler
1
你想要对元素进行循环旋转吗? - Nayuki
6个回答

12
也许你正在进行的练习涉及到这个方法,但是 ArrayList.add(int index,E element) 方法几乎可以满足你的需求。
"在此列表中指定的位置插入指定的元素。 将当前位于该位置的元素(如果有)和任何后续元素向右移动 (索引加1)。”(斜体字已添加)
所以只需要在位置0处添加列表中的最后一个元素,然后从末尾删除它即可。

4
这里有几个问题:
  1. Your for loop condition needs to exclude the zeroth element so it should be i > 0 otherwise you'll get to the point where you want to put element at position -1 to position 0 resulting in out of bounds error.
  2. Setting the first element to be the last should be outside the loop.
  3. listValues.set takes in an index in the list as the first parameter, you are giving it the object in the list

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

2

这是最简单的解决方案

Collections.rotate(list, rotationPosition);


2
最简单和最短的解决方案:(如果您不需要同时使用列表 - 因为在并发使用和迭代时,列表大小不应更改,否则会出现ConcurrentModificationException
public void shiftOneToRight() {
    
    listValues.add(0, listValues.remove(listValues.size() - 1));
    
}

0
my code to put a number in the right place in a List

            int nr = 5;  // just a test number
            boolean foundPlace = false;

            for(int i = 0; i < integerList.size(); i++){

                if(nr <= integerList.get(i)){
                    integerList.add(i,nr);
                    foundPlace = true;
                    break;
                }

            }
            if (!foundPlace)
                integerList.add(integerList.size(), nr);

正如上面的人所说,“integerList.add(element)”将指定的元素插入到此列表中的指定位置。当前元素会被移动...

0

输入数组列表:locationMap

循环移动从idxStart开始的LHS元素

移位后的输出列表:extendedList

// make extended list to behave like circular
List<String> extendedList = new ArrayList<>();
for (int i = idxStart; i < locationMap.size(); i++) { // current to end
    extendedList.add(locationMap.get(i));
}
for (int i = 0; i < idxStart; i++) { // 0 to current
    extendedList.add(locationMap.get(i));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接