I have five String[]
arrays, and I want to store them inside another array. How do I achieve this?
Can I create a java array of arrays
to hold them, and if so, what’s the correct syntax?
I have five String[]
arrays, and I want to store them inside another array. How do I achieve this?
Can I create a java array of arrays
to hold them, and if so, what’s the correct syntax?
The easiest way to store multiple String [ ] arrays inside another array is by using a 2D array:
public class ArrayOfArrays {
public static void main(String[] args) {
String[] arr1 = {"A", "B"};
String[] arr2 = {"C", "D"};
String[] arr3 = {"E", "F"};
String[] arr4 = {"G", "H"};
String[] arr5 = {"I", "J"};
String[][] arrayOfArrays = {arr1, arr2, arr3, arr4, arr5};
// Accessing elements
System.out.println(arrayOfArrays[2][1]); // Output: F
}
}
If you need dynamic resizing, use an ArrayList<String [ ]> instead of a fixed-size array:
import java.util.*;
public class ArrayOfArrays {
public static void main(String[] args) {
List<String[]> listOfArrays = new ArrayList<>();
listOfArrays.add(new String[]{"A", "B"});
listOfArrays.add(new String[]{"C", "D"});
listOfArrays.add(new String[]{"E", "F"});
// Accessing elements
System.out.println(listOfArrays.get(1)[0]); // Output: C
}
}
If the arrays store different data types, use an Object[][]
:
public class ArrayOfArrays {
public static void main(String[] args) {
Object[][] mixedArray = {
{"A", "B"},
{1, 2},
{3.5, 4.8}
};
// Accessing elements
System.out.println(mixedArray[1][1]); // Output: 2
}
}
It supports different data types in the same structure.