0

I just recently learned cloning in Java. There is deep cloning and shallow cloning. I was wandering what does the ArrayList does when objects added to it. Does it clon?

I made some tests with String object.

String s = new String("hello");
ArrayList<String> list = new ArrayList<String>();
list.add(s);
s = s.replace('h','y');
System.out.prinln(list.get(0));

It printed out "hello". So it does clon. Then I remembered from personal experience, when I add objects I wrote to an array, it doesn't clon. When I change the one in the array, original changes too.

I searched google, not sure because my lack of searching skills, I didn't find the answer I was looking for. Then I searched StackOverFlow, again nothing I was looking for.

So what is the deal with ArrayList? I am sorry if this question is duplicate, I really searched.

Some people didn't understand the question: Does ArrayList clon? (which is the main question I am looking the answer of) If not so why String did get cloned?

ossobuko
  • 851
  • 8
  • 25

2 Answers2

1

You can modify objects inside an array and the changes will remain if the object is mutable. String is inmmutable and you cant change it, every time you make any function/action over a String it returns a new String Object with the result.

ArrayList doesn't clone objects, its just an array of objects and if they are mutable you can get and modify them.

If you need a mutable string you can use the StringBuilder object:

StringBuilder string = new StringBuilder("Hi!");
string.append(" - concat new String");
System.out.println(string.toString());
kunpapa
  • 367
  • 1
  • 9
0

You can verify that manipulating the content of the list doesn't clone by checking its identityHashCode. It will remain the same.

David Soroko
  • 8,521
  • 2
  • 39
  • 51
  • I can find out If any object is clonned with this? WIll it be different for every object? – ossobuko Jan 26 '16 at 15:06
  • 1
    Yes, for example try: System.err.println(System.identityHashCode(s) + " vs. " + System.identityHashCode(s.replace('h', 'y'))); – David Soroko Jan 26 '16 at 15:14
  • 1
    Just to be clear, difference in identityHashCode indicates that the objects are different instances, this covers the clone scenario as well as String.replace when a new String is created – David Soroko Jan 26 '16 at 15:24