In this post, we will see how to create 2d Arraylist in java.
Best way to create 2d Arraylist is to create list of list in java.
1 2 3 |
List<List> arraylist2D = new ArrayList<List>(); |
Let’s create a program to implement 2d Arraylist java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package org.arpit.java2blog; import java.util.ArrayList; import java.util.List; public class Java2DArrayListMain { public static void main(String[] args) { // Intialize the arraylist List<List> arraylist2D = new ArrayList<List>(); // Create first list List list1=new ArrayList(); list1.add("List1_Str1"); list1.add("List1_Str2"); list1.add("List1_Str3"); // Create second list List list2=new ArrayList(); list2.add("List2_Str1"); list2.add("List2_Str2"); list2.add("List2_Str3"); // Create third list List list3=new ArrayList(); list3.add("List3_Str1"); list3.add("List3_Str2"); list3.add("List3_Str3"); list3.add("List3_Str4"); // Add individual list to arraylist2D arraylist2D.add(list1); arraylist2D.add(list2); arraylist2D.add(list3); //Let's retrieve element from the arraylist2D. System.out.println("2nd element in list3 : "+arraylist2D.get(2).get(1)); System.out.println("3nd element in list1 : "+arraylist2D.get(0).get(2)); System.out.println("1st element in list2 : "+arraylist2D.get(1).get(0)); } } |
Output:
2nd element in list3 : List3_Str2
3nd element in list1 : List1_Str3
1st element in list2 : List2_Str1
3nd element in list1 : List1_Str3
1st element in list2 : List2_Str1
That’s all about 2d Arraylist java.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.