Java assigns a value to the object, cautious with assignment symbol (=)

zhaozj2021-02-11  192

For objects, pay attention to the variable name is similar to the pointer, so please use the assignment symbol (=)! For example, the following code:

ArrayList ALALL = New ArrayList (); for (int i = 0; i <10; i ) {alall.add (String.Valueof (i));} / / 10 elements in Alall: 0- 9

Arraylist alprocessing = new arraylist ();

Alprocessing = alall; // [1] This is the problematic code //alprocessing.addall (aLAll); // [2] Here is the correct code that can achieve the purpose

For (int i = 0; i

For (int i = 0; i

/ * Open [1] Off [2] output is: (Yes wrong) 1st element: 1

2nd element: 3

3rd elements: 5

4th element: 7

5th element: 8

6th element: 9

Description: If statement [1], AlProcessing and ALALL point to memory in the same area, so remove the elements in AlProcess, which is also equivalent to removing the elements in Alall, so alal.size () is changing, and Alall The content inside is also changing. And if the statement is used [2], Alprocessing and Alall points to the unused area. * // * Open [2] Off [1] output is: (is correct) 1st element: 1

2nd element: 3

3rd elements: 5

4th element: 7

5th element: 9 * /

转载请注明原文地址:https://www.9cbs.com/read-5933.html

New Post(0)