Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Arraylist stores the reference and does not copy/create new objects. If you change the stored object reference, it will be reflected in the arrayList as well. Here is a sample code to demonstrate that:</p> <pre><code>package arraylistExample; import java.util.ArrayList; /** * Class represeting entity to be stored in Arraylist * */ class Person { private String name; private int age; private String address; public Person(String name, int age, String address) { super(); this.name = name; this.age = age; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", address=" + address + "]"; } } </code></pre> <p>.</p> <pre><code>/** * Public class to run the demo * */ public class ArraylistObjectModify { public static void main(String args[]) { // Add an arraylist and add elements to it ArrayList&lt;Person&gt; personList = new ArrayList&lt;Person&gt;(); personList.add(new Person("Juned",32,"Bangalore")); personList.add(new Person("Ahsan",31,"Delhi")); personList.add(new Person("Sniper",1,"Grave")); //Print list elements before change System.out.println("Arraylist pre objects modification"); System.out.println("----------------------------------"); for(Person person:personList) { System.out.println(person); } for(Person person:personList) { if(person.getName().equals("Juned")) { person.setName("ChangedJuned"); person.setAddress("Hola-lulu"); } } //Print list elements after change System.out.println("Arraylist post objects modification"); System.out.println("----------------------------------"); for(Person person:personList) { System.out.println(person); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload