function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Trif Cristian 7Trif Cristian 7 

Please help with this piece of code.

I'm kinda confused how this works line by line. Can someone explain it to me?

 

I have this piece of code, but I don't know how this works, line by line.

public class PassNonPrimitiveTypeExample {
               public static void createTemperatureHistory() {
                              List <Integer> fillMe = new List<Integer>();
                              reference(fillMe);
                              System.assertEquals(fillMe.size(),5);
 
                               List <Integer> createMe = new List<Integer>();
                               referenceNew(createMe);
                               System.assertEquals(createMe.size(),0);
               }
               public static void reference(List <Integer> m) {
                               m.add(70);
                               m.add(68);
                               m.add(75);
                               m.add(80);
                               m.add(82);
                }
                public static void referenceNew(List <Integer> m) {
                               m = new List{55, 59, 62, 60, 63};
               }
 }
 

Trif Cristian 7Trif Cristian 7

I'm very confused at these lines: reference(fillMe) and referenceNew(createMe);

Jainam ContractorJainam Contractor
Hi Tilf,

The above code, illustrates the use of reference() and referenceNew() method. 

In the reference(fillMe) function, it allocates the Memory which was hold by the fillMe list, and when we add an item to the Collection (List), it assigns that value to the same memory location which was allocated to the fillMe list. So as a result, modification which we made in reference(fillMe) function, are visible and size of fillMe list is 5.

In the referenceNew(fillMe) function, When the “new” function is called, new memory is allocated.

The copy of the memory address passed as a parameter is overwritten with the address of the newly allocated memory.  The original, however, is not overwritten. That change in address is not known to the caller. So when we add a new member to the list, it is saved/ stored in the new Address and not the original address of the List fillMe. As a new memory was allocated and no members were added to the original memory address of the list, the original list/ memory is still empty as it was and as a result size of the List fillMe is still 0.

Please let me know if it helped or you need any more assistance.

Please mark this is as the solution if it solved your purpose.

Thanks,
Jainam Contractor,
Salesforce Consultant
Varasi LLC
www.varasi.com