2015-09-03 56 views
0

所以我嘗試創建一個方法,將arraylist中的所有元素向右移動,最後一個元素將成爲第一個元素。當我運行代碼時,我被告知我有一個越界錯誤。以下是我迄今爲止:如何在java中將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); 
    } 

} 
+0

[This](http://stackoverflow.com/questions/13129043/shifting-array-to-the-right-homework)可能會幫助你.. –

+0

所以你想做一個元素的圓形旋轉? – Nayuki

回答

2

的幾個問題在這裏:

  1. 您的循環條件需要排除零個元素,所以應該是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);  
    } 
    
+0

我想通了!感謝您的幫助。 –

2

也許這是你工作的鍛鍊,但ArrayList.add(int index,E element)方法幾乎是你想要的。 「

」將指定元素插入此列表中的指定位置。將當前位於該位置(如果有)和任何後續元素的元素向右移動(在其索引中加1)。 (斜體添加)

所以,只需在位置0添加列表中的最後一個元素。並從末尾刪除它。

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)」將指定的元素插入到列表中的指定位置。當前移位元素...

相關問題