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
dmchengdmcheng 

List popluation not working in a for loop

Hello.  I'm trying to populate a list with some dummy records so I can do some unit testing.  However, when I do a for loop, the list remains null and the assertion fails.  I've tried two different assignment techniques but neither works.  If I get rid of either for loop and just put in a line j = 0, then the list is populated.  I can't figure out what I'm doing wrong here.

Thanks
David
Code:
public class Util {

 static testmethod void testAllTriggers() {
  Integer i, j;
 
  //Set up a contact and payments for testing.
  Contact person = new Contact(FirstName = 'John', LastName = 'Qwertyuiop');
  insert person;
  Id contactID = [select id from Contact where LastName = 'Qwertyuiop'].Id;
  Membership_Payment__c[] payments = new Membership_Payment__c[23];

//THIS LOOP FAILS TO POPULATE
//  for (j = 0; j == 22; j++) {
//   payments[j] = new Membership_Payment__c(Contact__c = ContactID, Name = (2010 + j).format(),
//    Posted_Date__c = Date.newInstance(2010 + j, 1, 2), Amount__c = 20);
//  }

//THIS LOOP ALSO FAILS TO POPULATE
//  for (j = 0; j == 22; j++) {
//   payments.add(new Membership_Payment__c(Contact__c = ContactID, Name = (2010 + j).format(),
//    Posted_Date__c = Date.newInstance(2010 + j, 1, 2), Amount__c = 20));
//  }

  system.assertEquals(date.newInstance(2010, 1, 2), payments.get(0).Posted_Date__c);  


 

BoxBox

try replacing 'j ==22' with 'j <= 22'

dmchengdmcheng
If I do "j < 23", then it does work.  Thanks!
BoxBox

No problem, the for loop will execute until the condition is no longer true.  As you had j == 22 this was never true and so would never execute.

dmchengdmcheng
I don't understand - doesn't j keep incrementing until 22?  Or is this just a rule of Apex for loops -- that you cannot do equality comparisons?
DurglesDurgles

For loops continue to loop until the boolean evaluates to FALSE.  In other words:

 

for (j = 0; j == 22; j++) {}

 

j = 0;

does j equal 22? No.  Returns false.

Close loop.

 

for (j = 0; j <= 22; j++) {} 

j = 0;

is j less than or equal to 22? Yes.  Returns true.

Do what's in the brackets.

Increase j by 1. (j now equals 1)

is j less than or equal to 22? Yes.  Returns true.

Do what's in the brackets.

Increase j by 1. (j now equals 2)

 

is j less than or equal to 22? Yes.  Returns true.

Do what's in the brackets.

Increase j by 1. (j now equals 3)

 

etc. etc.

 

Cheers,

Jody