How to extend the size of an array in Java

Java 8Object Oriented ProgrammingProgramming

An array has a fixed number of values and its size is defined when it is created. Therefore, the size of the array cannot be changed later. To solve this problem, an ArrayList should be used as it implements a resizable array using the List interface.

A program that demonstrates ArrayList in Java is given as follows −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      ArrayList<String> aList = new ArrayList<String>();
      aList.add("Apple");
      aList.add("Melon");
      aList.add("Orange");
      aList.add("Mango");
      aList.add("Grapes");
      System.out.println("ArrayList elements are:");
      for(String i:aList) {
         System.out.println(i);
      }
   }
}

Output

ArrayList elements are:
Apple
Melon
Orange
Mango
Grapes

Now let us understand the above program.

First the ArrayList is created. Then elements are added to it using add(). Finally, the ArrayList elements are displayed using for loop. A code snippet which demonstrates this is as follows −

ArrayList<String> aList = new ArrayList<String>();
aList.add("Apple");
aList.add("Melon");
aList.add("Orange");
aList.add("Mango");
aList.add("Grapes");
System.out.println("ArrayList elements are:");
for(String i:aList) {
   System.out.println(i);
}
raja
Published on 09-Jan-2019 10:17:53
Advertisements