-2

Say we have an object and we add it into an ArrayList. Does java create a new object and add it into the list, or it uses the same object we passed in and put it into the arraylist?

Zoe
  • 11
  • Does this answer your question? [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – luk2302 May 19 '21 at 17:16
  • God question! It adds the same object, not a copy – Scrapper142 May 19 '21 at 17:16
  • You are adding a reference to the object to the list. You can test this yourself by creating the object, adding it to the list, modifying the object, then checking the object in the list. – Dave Newton May 19 '21 at 17:17
  • [Add an object to an ArrayList and modify it later](https://stackoverflow.com/q/7080546) – 001 May 19 '21 at 17:17
  • There is no way to copy an arbitrary Java object. – khelwood May 19 '21 at 17:21

1 Answers1

0

It uses the existing object, actually it uses it's reference, reference is put inside list. If you keep reference in another variable outside of list, you can edit it and the value is going to change inside of list also.

public static void main(String[] args) {
    List<StringBuilder> list = new ArrayList<>();
    StringBuilder str1 = new StringBuilder("foo");
    StringBuilder str2 = new StringBuilder("bar");

    list.add(str1);
    list.add(str2);

    str1.append(" baz");

    System.out.println(str1);
    System.out.println(list);
}

This block of code would give you an idea of this because this is the output

foo baz
[foo baz, bar]
Filip
  • 609
  • 7
  • 18