Issue
So I am trying to create a method that shifts all of the elements in an arraylist to the right and the last element will become the first element. When I run the code, I am told I have an out of bounds error. Here is what I have so far:
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);
}
}
Solution
A few problems here:
- 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 position0
resulting in out of bounds error. - Setting the first element to be the last should be outside the loop.
listValues.set
takes in an index in the list as the first parameter, you are giving it the object in the listpublic 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); }
Answered By - kevin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.