Multidimensional Collections in Java
In Java, we have a Collection framework that provides functionality to store a group of objects. This is called a single-dimensional ArrayList where we can have only one element in a row. Geek but what if we want to make a multidimensional ArrayList, for this functionality for which we do have Multidimensional Collections (or Nested Collections) in Java.
Multidimensional Collections (or Nested Collections) is a collection of groups of objects where each group can have any number of objects dynamically. Hence, here we can store any number of elements in a group whenever we want.
Single dimensional ArrayList : [121, 432, 12, 56, 456, 3, 1023] [Apple, Orange, Pear, Mango]
ArrayList <Object> x = new ArrayList <Object>();
Need for Multidimensional Collections
Unlike Arrays, we are not bound with the size of any row in Multidimensional collections. Therefore, if we want to use a Multidimensional architecture where we can create any number of objects dynamically in a row, then we should go for Multidimensional collections in java.
Syntax: Multidimensional Collections
ArrayList<ArrayList<Object>> a = new ArrayList<ArrayList<Object>>();
Multidimensional ArrayList: [[3, 4], [12, 13, 14, 15], [22, 23, 24], ]
Let us quickly peek onto add() method for multidimensional ArrayList which are as follows:
- boolean add( ArrayList<Object> e): It is used to insert elements in the specified collection.
- void add( int index, ArrayList<Object> e): It is used to insert the elements at the specified position in a Collection.
2D ArrayList : [, [366, 3, 4, 22, 1000, 6, 576], [3, 84], [83, 6684, 776], [8, 9, 10, 11]]
Now let us see the same implementation of multidimensional LinkedHashSet and in order to show how it behaves differently. Similarly, we can implement any other Collection as Multidimensional Collection as depicted below:
HashSet< HashSet<Object> > a = new HashSet< HashSet<Object> >();
Note: LinkedHashSet class contains unique elements & maintains insertion order. Therefore, in Multidimensional LinkedHashSet uniqueness will be maintained inside rows also.
2D LinkedHashSet : [[Apple, Orange], [Tea, Coffee, Milk, Water], [Tomato, Potato, Onion]]