get method return value

feel free :

i run following codes in eclipse:

ArrayList<StringBuilder> list = new ArrayList<StringBuilder>();
ArrayList<Integer> alist = new ArrayList<Integer>();

// add some elements ti list
list.add(new StringBuilder("hello"));
list.add(new StringBuilder("2"));
list.add(new StringBuilder("hi"));
list.add(new StringBuilder("this"));

// add some elements to alist
alist.add(4);
alist.add(9);


//get method
StringBuilder a = list.get(3);
a.append(" is a good day");
int b = alist.get(1);
b = 7;

// print the list
System.out.println("LinkedList:" + list);
System.out.println("ArrayList:" + alist);

and result is here

LinkedList:[hello, 2, hi, this is a good day]
ArrayList:[4, 9]

It looks like get method returns a shallow copy of list element (in the case of StringBuilder) to the a, but returns a deep copy (in the case of integer) to the b! why it happened? Do the get method return a deep or shallow copy of list's elements?

Eran :

get returns a reference to the List element, not a copy (neither deep nor shallow).

In the first snippet you mutate the object referenced by variable a, so the List is also affected:

StringBuilder a = list.get(3);
a.append(" is a good day");

In the second snippet you assign a new value to the variable b, which doesn't affect the List:

int b = alist.get(1);
b = 7;

In order for your first snippet to behave as the second, you should write:

StringBuilder a = list.get(3);
a = new StringBuilder(" is a good day");

and the List won't be affected.

On the other way, you can't make the second snippet behave as the first. Even if you assigned the List element to an Integer variable, you can't call any method that would mutate it, since Integer is immutable.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=94170&siteId=1