public static ArrayList<Integer> reverse (ArrayList<Integer> n) {
ArrayList<Integer> result = new ArrayList<Integer>();
for(int i = 0; i < n.size(); i++) {
int j = n.size() - i - 1;
result.add(i, n.get(j));
}
return result;
}
but if i enter an array 1,2,3,4,5,6,7,8,9,10
the result is 10,9,8,7,6,5,4,3,2,10
Where is my mistake?
Actually, what you have there works fine. But you can simplify your
for-loop by iterating ‘backwards’:Oh, and one more thing I should mention. When you declare the list
result, you might want to specify its capacity, since you know what it will be. i.e.: