Search code examples
apex-codevisualforce

How to write a multidimensional array in APEX


I have a two dimensional array in Java:

private static final string[][] namestr = { { John, Mark, David,
}, { Peter, Ken, Mary,
}, { Fisher, Alice, Chris,
}, { Tod, Jen, Joe, Morton
}};

How can I write this Two dimensional array in Apex?

I still need to keep it as a two dimensional array with [4][3],

Thanks


Solution

  • You can have a list of lists. I think the proper term is "jagged array" as opposed to "multidimensional array". What I mean is that it's up to you to make sure each internal list has same size; language itself won't enforce this in any way. But since your last row has 4 items instead of 3 looks like you're OK with that.

    http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_collections_lists.htm

    Because lists can contain any collection, they can be nested within one another and become multidimensional. For example, you can have a list of lists of sets of Integers. A list can contain up to four levels of nested collections inside it.

    List<List<String>> names = new List<List<String>>{
        new List<String>{'John', 'Mark', 'David'},
        new List<String>{'Peter', 'Ken', 'Mary'},
        new List<String>{'Fisher', 'Alice', 'Chris'},
        new List<String>{'Tod', 'Jen', 'Joe', 'Morton'}
    };
    
    System.debug(names[1]);
    System.debug(names[1][2]);
    

    There's no size limit, standard stuff like heap space limit applies. If you plan to pass them to Visualforcethe limit is 1000 items though (10K if your page has readonly attribute set).