Reputation: 1
I have to make a method that can reverse all elements of ArrayList ... For exmaple, if my list have <12 1 34 56 43> elements. then it should reverse the whole list. <43 56 34 1 12>. I've tried this method, but it doesn't work. Here is the method
public void reverse() {
int size=0;
for (int i = 0, j = size - 1; i < size && j >= 0; i++, j--)
{
int temp = j;
j = i;
i = temp;
}
}
when I call this method list.revese(). it doesn't reverse the list. Can anyone please help me out!!!
Upvotes: 0
Views: 801
Reputation: 721
Your code deals with the index but not the actual element of the index. Also note that if j < i, you are doing the reversing twice, thus there will be no effect.
public void reverse(List<Integer> list) {
int size=list.size();
for (int i = 0, j = size - 1; i < size && j >= 0 && i <= j; /** i must be smaller. */ i++, j--)
{
int temp = list.get(j);
list.set(j, list.get(i));
list.set(i,temp);
}
}
Upvotes: 3
Reputation:
Initialize 'size' variable to the length of the ArrayList. You are initializing it to 0.
Upvotes: 0
Reputation: 1670
Use the ArrayList object, and then after building your array you can just run the following to reverse the contents:
Collections.reverse(your ArrayList Here);
Upvotes: 2