In the previous tutorial we have seen a static list declaration and usage with different types of data types.Now in this part of the tutorial we will get to know a dynamic list.
Java Dynamic List :
When we create any real time application like shopping app where cart is designed or storing users as contact’s or fetching data from databases we use list.
And now we can’t assess the list size so we need to use java dynamic list’s to fulfill the requirement.
Initialize a list
ArrayList<String> list = new ArrayList<>();
Now we will try to add 10 String’s into the Array List here there is no limit of String’s we can add more than 10 String too.
list.add("One"); list.add("Two"); . . . . list.add("Ten");
Using a for loop we can parse the loop based on the index position
for(int i = 0; i < list.size(); i++){ System.out.println(list.get(i)); }
String Array List:
public static ArrayList<String> list = new ArrayList<>(); public static void main(String args[]){ list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); list.add("Five"); list.add("Six"); list.add("Seven"); list.add("Eight"); list.add("Nine"); list.add("Ten"); for(int i = 0; i < list.size(); i++){ System.out.println(list.get(i)); } }
Integer Array List:
ArrayList<Integer> list = new ArrayList<>();
Add number’s
list.add(1); list.add(2); list.add(3); list.add(4); list.add(5);
public static ArrayList<Integer> list = new ArrayList<>(); public static void main(String args[]) { list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } }