What I Have: A static ArrayList which stores Integers. I add an Integer via reference to it and then I change the value but the value is not updated.
import java.util.ArrayList;
public class Main {
public static final ArrayList<Integer> integers = new ArrayList<>();
public Integer integer;
void addInteger(Integer i){
integers.add(i);
}
public static void main(String[] args) {
Main main = new Main();
main.integer = 3;
integers.add(main.integer);
main.integer = 4;
System.out.println(integers.get(0));
}
}
Output: 3
Question: Why is the output not 4 ?
Further Question based on follow ups: What is really stored within the ArrayList ?
EDIT BASED ON THE ACCTPTED ANSWER:
Since integer
is an Integer
(and not an int
) the 3
is autoboxed. The ArrayList
stores actually Integer.valueOf(3)
.