0

I am having trouble understanding how objects are added to a List.

This is a sample of code where an int[] is added to a List -

    List<int[]> list = new ArrayList<>();
    int[] element = {2,3};
    list.add(element);
    System.out.println(list);   //[[2,3]]
    element[1] = 45;
    System.out.println(list);   //[[2,45]]

I am not sure how exactly objects are added to a List. Is a copy of the Object added? I was trying to find if it works the same for primitives, so here is a code sample for that -

    List<Integer> list = new ArrayList<>();
    int obj = 25;
    list.add(obj);
    System.out.println(list);   //[25]
    obj=56;
    System.out.println(list);   //still [25]

The add function documentation on Oracle doesn't mention how the objects are added, just that it is a boolean function that adds the element at the end unless otherwise specified. I know that Java works with reference to objects, but with respect to this problem, what does it mean exactly?

Will be obliged if you could help me understand this, thank you in advance

Anurag
  • 3
  • 1
  • 5
  • 1
    Does this help? [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Abra Sep 02 '21 at 04:12
  • This has nothing to do with adding to lists. `Integer`s are _always_ not modifiable, and arrays are _always_ modifiable. `obj=56;` is not modifying an object. It's just reassigning the variable `obj` to 56. – Sweeper Sep 02 '21 at 04:20
  • @Abra I did go through that question, but I wasn't aware that Integers were not modifiable and arrays are. – Anurag Sep 02 '21 at 04:42
  • Thank you @Sweeper, your explanation cleared some misconceptions I had – Anurag Sep 02 '21 at 04:42

1 Answers1

0

All primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old.