Arrays, lists and copying elements

    Person person = new Person(); //Created: Person [name=null]
    person.setName("Bartek");
    List<Person> persons = new ArrayList<>();
    persons.add(person);
    System.out.println("Persons=" + persons); // Persons=[Person [name=Bartek]]

    List<Person> persons2 = new ArrayList<>(persons);

    person.setName("Kazek");
    System.out.println("Persons=" + persons); // Persons=[Person [name=Kazek]]
    System.out.println("Persons2=" + persons2); // Persons2=[Person [name=Kazek]]

    persons.remove(0);
    System.out.println("Persons=" + persons); // Persons=[]
    System.out.println("Persons2=" + persons2);  // Persons2=[Person [name=Kazek]]   

Output:

Created: Person [name=null]
Persons=[Person [name=Bartek]]
Persons=[Person [name=Kazek]]
Persons2=[Person [name=Kazek]]
Persons=[]
Persons2=[Person [name=Kazek]]

Note:
persons2 = new ArrayList(persons) makes a safe (deep) copy of all references in persons list. So removing an element from persons does not affect persons2 list. However, modification of a particular person internal state is reflected in both of the list.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s