First, let's take a look at the differences between the following two sections of code:
Code 1:
List <task> tasks = new arraylist <task> ();
Task [] alltask = DemoData. gettasksdata ();
For (INT I = 0; I <alltask. length; I ++ ){
Tasks. Add (alltask [I]);
}
--------------------------------------------------
Code 2:
List <task> tasks = new arraylist <task> ();
For (INT I = 0; I <DemoData. gettasksdata (). length; I ++ ){
Tasks. Add (DemoData. gettasksdata () [I]);
}
-------------------------------------------------
From the code above, we can see that the differences between the two methods are mainly reflected in: one is to store the results returned by the function using temporary variables, and the other is to directly use the return values of function calls.
So what are the differences between them?
Originally, For the first method, the function was called only once, while the second method was called multiple times, people who use the second method seem to want to save some "Unnecessary" variables to save space and make the code more concise, which is actually counterproductive, because each function call will return a "Temporary Variable", and if DemoData. gettasksdata () has a large amount of memory operations, so this overhead is quite huge.
If you do not have high memory requirements, you will not find any problems, but if DemoData. gettasksdata () has memory operations, especially object creation operations, and there are some dependencies or associations between objects. The second method calls DemoData every cycle. gettasksdata () is used once, so the relationships between objects are not established. Each time tasks adds a task in another version of tasks data, after that, when using tasks, problems will occur: either a task's pre-task cannot be found, or it is null, and cannot be found because the association relationship is not correctly established, null because the "useless object" applied for multiple times has been released.
So we can sum up one point from this example,For a function with a returned value, it is best to use a variable to save the returned value. You can directly use the variable later.
(Of course, let's talk about deep copy and shortest copy ). Especially for Java, Because Java uses the address by default to compare whether two objects are equal, so the second method is often surprising: No matter how you system. out. println outputs are always correct. However, they only have the same content, but they are not actually the same objects.