0% found this document useful (0 votes)
4 views2 pages

ArrayList Modifications in Java

The document explains the behavior of ArrayLists in Java when dealing with mutable objects like StringBuilder. It highlights that direct assignment of ArrayList references leads to shared modifications, while using addAll creates a new list that reflects changes to individual elements but not structural changes like add or remove. An example code demonstrates these concepts with StringBuilder objects in ArrayLists.

Uploaded by

Hizkiyas Eyasu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

ArrayList Modifications in Java

The document explains the behavior of ArrayLists in Java when dealing with mutable objects like StringBuilder. It highlights that direct assignment of ArrayList references leads to shared modifications, while using addAll creates a new list that reflects changes to individual elements but not structural changes like add or remove. An example code demonstrates these concepts with StringBuilder objects in ArrayLists.

Uploaded by

Hizkiyas Eyasu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

Given: this doesn't work for immutable objects like String

1. if you directly assign one ArrayList reference to another, modifying the common
list elements in any of the lists will be reflected in both of the lists.

2.
if arrayList1 is used to create arrayList2 using [Link](arrayList1),
modifying the common list elements using append, replace...(operated/performed on
individual elements) in any of the lists will be reflected in both of the lists.
But other modifications like add, remove, set,... (operated/performed on either of
the lists arrayList1 or arrayList2) will be reflected on the corresponding list.

eg:

import [Link];
import [Link];
import [Link];
import [Link];

public class IC2 {


public IC2(String s) {
}

public static void main(String[] args) {

ArrayList<StringBuilder> alb = new ArrayList<>();


StringBuilder aa = new StringBuilder("AA");
[Link](aa);
[Link](new StringBuilder("BB"));

ArrayList<StringBuilder> alb2 = new ArrayList<>();

[Link](alb);

// [Link]("[Link](0, new StringBuilder(\"SB\"))");

[Link](0, 1, "#"); //reflects both


// [Link](0, new StringBuilder("##"));//reflects this(alb2)
//[Link](0);
[Link](new StringBuilder("NEW"));
// for (StringBuilder val : alb2) {
// //[Link](val);
// //[Link](0, new StringBuilder("##"));
// [Link](1, 2, "$$");
//// [Link]("&&");
// }

[Link]("alb");
for (StringBuilder val : alb) {
[Link](val);
}

[Link]("alb2");
for (StringBuilder val : alb2) {
[Link](val);
}
}
}

You might also like