Avoid Multidimensional Arrays and Nested Lists
ID |
java.avoid_multidim_collection |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
best-practice, efficiency |
Description
Reports multidimensional arrays (e.g., int[][]) and nested list types (e.g., List<List<X>>). Two parallel single-dimension arrays are more memory-efficient and cache-friendly than a multidimensional array or nested collection structure.
Rationale
A Java multidimensional array like int[][] is an array of array references, not a contiguous block of memory. Each inner array is a separate heap object with its own header and possible different GC timing. This indirection harms CPU cache locality and increases GC overhead. Nested lists compound the problem with additional object-per-element overhead.
// Bad: multidimensional array -- array of array references
int[][] matrix = new int[100][100];
// Bad: nested list -- heavy object overhead
List<List<Integer>> grid = new ArrayList<List<Integer>>();
Remediation
Use parallel single-dimension arrays or a flat array with index arithmetic. For small fixed-size structures, consider dedicated data classes.
// Good: flat array with index arithmetic
int[] matrix = new int[100 * 100];
int value = matrix[row * 100 + col];
// Good: parallel arrays
int[] xCoords = new int[100];
int[] yCoords = new int[100];