简体   繁体   中英

get method return value

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?

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.

In the case of StringBuilder a = list.get(3); you get a reference to element at index 3 assigned to variable a , modifying using a will affect element at index 3 . where as int b = alist.get(1); you get a copy of element at 1 assigned to variable b so modifying it will not affect element at 1 . there is not connection between b and element at 1 after assignment .

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

Indeed you create a shallow copy of your list element in int b =... . As your List contains Objects of Type Integer you make a new assignment to a primitive integer here, while with the StringBuilder you work on exactly the same object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM