The modified ArrayList returned by the get method

I have below two situations related to the ArrayList method get, one with a custom class and one with the String class:

1. The following is an example of modifying a Custom ArrayList element:

ArrayList<MyClass> mTmpArray1 = new ArrayList<MyClass>();
MyClass myObj1 = new MyClass(10);  
mTmpArray1.add(myObj1);

MyClass myObj2 = mTmpArray1.get(0);  
myObj2.myInt = 20;

MyClass myObj3 = mTmpArray1.get(0);  
Log.d(TAG, "Int Value:"+myObj3.myInt);    // Prints "20" 

2. The following is an example of modifying a String ArrayList element:

ArrayList<String> mTmpArray2 = new ArrayList<String>();  
mTmpArray2.add("Test_10");

String myStr1 = mTmpArray2.get(0);
myStr1 = "Test_20";

String myStr2 = mTmpArray2.get(0);
Log.d(TAG, "Str Value:"+myStr2);  // Prints "Test_10" 

Therefore, in the case of MyClass ArrayList, when I call getand change the value, I see that the change is reflected when I again get.

But also, when I change the String ArrayList, the changes are not reflected.

What is the difference between the method getin both scenarios?
Is it that in the case of String, the String class creates a deep copy and returns a new object, while in the case of a custom class, a shallow copy is created?

, "LinkedHashMap", "HashMap" "List"?

+4
6

.

, , :

myObj2.myInt = 20;

, :

myStr1 = "Test_20";

String , String, , , :

myStr1.setSomething(...);

, , , , :

myObj2 = new MyClass (...);
+3

. .

String myStr2 = mTmpArray2.get(0);, ArrayList, (- String) String (myStr2), ArrayList.

myStr1 = "xxx", ArrayList, () ( myStr1), ArrayList .

: Java

( ), . Java.;)

. : MyClass myObj1 = new MyClass(10); () . factory, . , (, , , ).

A () : MyClass myObj = MyClass.createInstanceWithCapacity(10); // i've invented the name because I don't know what your 10 is, but look at both, which one do you think is easier to understand upon first glance?

. - , .;)

+2

"Immutablity"

, String (), / , . , , ,

,

String s = "Old String";
System.out.println("Old String : "+s); // output : Old String

String s2 = s;
s2 = s2.concat(" made New");
System.out.println("New String : "+s2); // output : Old String made New
System.out.println("Old String is not changed : "+s); // output : Old String
+1

"". , ArrayList, , , get.

:

MyClass myObj2 = mTmpArray1.get(0);  
myObj2.myInt = 20;

MyClass ArrayList 0, .

:

String myStr1 = mTmpArray2.get(0);
myStr1 = "Test_20";

String , myStr1 , ( "Test_20" ). myObj2 = new MyClass(20); .

, , , , . , .

, Java , , .

0

.

myStr1 = "Test_20";

String, myStr1. String myStr1, String. ArrayList.

MyClass .

myObj2.myInt = 20;

, ArrayList, .

0

.

:

  • myObj2
  • , 'myObj2', int

:

String myStr1 = mTmpArray2.get(0);
myStr1 = "Test_20";

:

  • myStr1.
  • 'myStr1' "Test_20"

, , , . , , - , , , - , , , .

string, set (x, "Test_20" ).

0
source

All Articles