1
import java.util.*;

public class Metodo {

    public static void main(String[] args) {
        ArrayList<Integer> a = new ArrayList();
        a.add(1);
        a.add(2);
        a.add(3);
        a.add(4);
        a.add(5);
        Metodo.inverte(a);
        for(int i=0; i<a.size(); i++) {
            System.out.println(a.get(i));
        }
    }

    public static void inverte(ArrayList<Integer> a) {
        ArrayList<Integer> other = new ArrayList();
        other = a;
        for(int i=0; i<a.size(); i++) {
            a.set(i, other.get(other.size()-i-1));
        }
    }
}

This method should ivert the numbers in the ArrayList so it should print "5 4 3 2 1" but it prints "5 4 3 4 5" instead. Why?

enguerran
  • 3,193
  • 3
  • 26
  • 42

4 Answers4

5
other = a;

does not create a copy of the original List.

Both a and other reference the same List object, so when you call a.set(0,other.get(other.size()-1), you lose the original value of other.get(0).

You should use:

ArrayList<Integer> other = new ArrayList<>(a);

to create a copy of the original List and remove other = a;

Eran
  • 387,369
  • 54
  • 702
  • 768
2

Eran already answered this question, but a simple note here. that you can reverse ArrayList using:

Collections.reverse(arrayList)
Mahmoud Hanafy
  • 1,861
  • 3
  • 24
  • 33
2

You can add the items of a into other in the reverse order and return the result:

public static ArrayList<Integer> inverte(ArrayList<Integer> a) {
    ArrayList<Integer> other = new ArrayList<>();
    for(int i = a.size() - 1; i >=0 ; i--) {
        other.add(a.get(i));
    }
    return other;
}

So you do:

a = Metodo.inverte(a);
forpas
  • 160,666
  • 10
  • 38
  • 76
0

As you can see in answers made, you can learn two things about your programing language:

  1. What is the difference between a copy and a reference? See @Eran's answer

    If you change the order of the items in a list when you make a loop on it, you will encounter problems.

  2. How standard libraries and built-in types can help you? See @Mahmoud Hanafy's answer

    You need to spend time to know what the language and its ecosystem can afford to you. For instance, it is very important you understand that reverse a collection is something very common, and on every new line you have to ask you: how other developers handle this.

Community
  • 1
  • 1
enguerran
  • 3,193
  • 3
  • 26
  • 42