Is it possible to create lists dynamically using array notation as below for naming purposes? If so, how do you accomplish it?

Here's an example of what I'm trying to accomplish. I've searched extensively but haven't seemed to be able to find a reference that shows how to do something like this; at least not that I could recognize.


   list<Event>MyEvent[i] = new list<Event>();


In essence, I don't know how many lists I'm going to need and want to be able to distinguish between them in a particular use case. They need to be ordered lists, so maps and sets are of no use to me, thus the reason for my question.

I did see a reference to creating an array of Lists or "List of Lists", but received an out of bounds list exception when I attempted to add to MyList[0].


Using "List of Lists" try the following:

if (myList == null)
    myList = new List <List <Event>> ();

for (i = 0; i < x; i++)
    if (myList.size() == 0)
        myList.add(new List <Event> ());
    else if (myList[i] == null)
        myList.add(i, new List <Event> ());

    // your code
    // myList[i].add(yourEventObject);
  • 1
    Made a quick change because there was a question about using add(index, object) the other day — a list of size zero chucks an OOB exception if you try to add to 0! – Matt Lacey Oct 6 '13 at 23:40
  • Clever idea, but I'm getting a list of bounds exception both when Apex executes the if(myList == null) statement and when it attempts to add MyList[i] to the list of <list<event>>. Just saw LaceySnr's Comment. My tests would seem to confirm. What change was made, oh, to my post? Gotcha, Thnx! – crmprogdev Oct 7 '13 at 0:02
  • Click on "edited XX mins ago" above @LaceySnr's avatar and you should be able to see the change. – Boris Bachovski Oct 7 '13 at 0:07
  • yes, just refreshed. Thnx. Note though that I'm still getting the out of bounds on the if statement, so it appears this would need a "try catch". – crmprogdev Oct 7 '13 at 0:09
  • Yeah if you're testing to see if element 3 exists and the list is only 3 items long that will chuck an OOB exception still. Do you really need to use add(i, object)? You appear to be running through things sequentially so can you not just use add(object)? – Matt Lacey Oct 7 '13 at 0:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.