I'm creating a class where I have come to the conclusion that the most efficient method to proceed is with an array variable that works as a matrix. I'm not sure how many columns or rows I will need so it can't have a specific length or size. 

Is there a way to declare a variable that works as a matrix? 

Example: Variable[Row Number, Column Number]

1 Answer 1


You can create a 2-dimensional list by using a List<List<Object>>. Entries should then be retrievable with a two bracket syntax, e.g.:

List<List<integer>> doubleList = new List<List<Integer>>();
for(integer i = 0; i < 3; ++i)
    doubleList[i] = new List<integer>();
    for(integer j = 0; j < 3; ++j)

You can nest more than two lists if you need a 3D or 4D array, though per sfdcfox's answer there is a limit of 7 levels of nesting.

  • Perfect! This is exactly what I was looking for. Thank you very much. Commented Jul 11, 2017 at 21:55
  • 1
    FYI, there is a limit of 7 levels of nesting... see this question for details.
    – sfdcfox
    Commented Jul 12, 2017 at 2:36
  • @sfdcfox Thanks, I suppose if you had a requirement for more than 7 levels you could use a Map<String, Object> where the map keys were n,m,z,... Commented Jul 12, 2017 at 11:47
  • @IllusiveBrian It depends on the use case. By the time you get to the seventh level, you'll find that the code would be painful to even write, much less maintain. Two possible choices might be Map<CustomKey, Value>, where CustomKey is a class that implements hashCode/equals, or you might even do a Map<Object, Object>, where the value may be yet another Map<Object, Object>, as long as you need. The compiler limits you to seven levels, but using Object is a way to get further, it just requires more discipline. A simple string might work, too, but depends on the use case.
    – sfdcfox
    Commented Jul 12, 2017 at 12:45
  • @sfdcfox The code being painful to write is pretty much true whichever method you use. Also, I'm a bit surprised that getting around the limit using an Object doesn't throw a runtime error. Commented Jul 12, 2017 at 12:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .