I am struggling to write a code sample where an object can belong to an array and arraylist simultaneously and where modifying in arraylist or the array changes the object? See example where I was expecting Monkey from both Array and Arraylist after change but only Array changed
import java.util.ArrayList;
public class ArrArrList {
public static void main(String[] args)
{
// Creating an ArrayList of Object type
ArrayList<Object> arr = new ArrayList<Object>();
String[] strArray = new String[3];
strArray[0] = "one";
strArray[1] = "two";
strArray[2] = "three";
String[] str = strArray;
// Inserting String value in arrlist
arr.add(str[0]);
arr.add(str[1]);
arr.add(str[2]);
System.out.print(
"ArrayList after all insertions: ");
display(arr); **// Prints one two three**
System.out.print(
"Array after all insertions: ");
for (int i = 0; i < 3; i++) {
System.out.print(str[i] + " "); **// Prints one two three**
}
System.out.println();
strArray[2] = "Monkey";
//arr.set(2,strArray[2]);
System.out.print(
"ArrayList after change: ");
display(arr); **// Prints one two three**
System.out.print(
"Array after change: ");
for (int i = 0; i < 3; i++) {
System.out.print(str[i] + " "); **// Prints one two Monkey**
}
System.out.println();
}
// Function to display elements of the ArrayList
public static void display(ArrayList<Object> arr)
{
for (int i = 0; i < arr.size(); i++) {
System.out.print(arr.get(i) + " ");
}
System.out.println();
}
}

strArray[2] = "Monkey";does is it puts into the array a reference to a string object that is not referenced from the list.ArrayListand the array each have its own references. So changing the reference in one will never affect the other.