Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate the use of ArrayList.

Java Code Example — Collection Programs

ADVERTISEMENT

Java Program to demonstrate the use of ArrayList.

Objective

Write a Java program to demonstrate ArrayList operations (add, find, remove).

Algorithm / Approach

  1. Import java.util.*.
  2. Instantiate an ArrayList<Integer>.
  3. Use a loop to continuously ask the user for elements and use al.add(x) to append them to the list.
  4. Use al.indexOf(x) to search for an element and return its position.
  5. Use al.remove(index) to delete an element from the list.
Test.java
import java.util.*;
class Test {
 ArrayList<Integer> al;
 Scanner s;
 Test() {
  al = new ArrayList<Integer>();
  s = new Scanner(System.in);
 }
 void addElement() {
  char c = 'y';
  while(c=='y') {
   System.out.print("Enter Element: ");
   int x = s.nextInt();
   al.add(x);
   System.out.print("Want to Add[y/n]: ");
   try {
    c=(char)System.in.read();
   }
   catch(Exception e) { }
  }
 }
 void find() {
  System.out.print("Element to find: ");
  int x = s.nextInt();
  int i = al.indexOf(x);
  if(i == -1) {
   System.out.println("NOT in List");
  }
  else {
   System.out.println("Find at "+(i+1));
  }
 }
 void show() {
  System.out.println(al);
  System.out.println("Size: "+al.size());
 }
 void delete() {
   System.out.print("Element to delete: ");
  int x = s.nextInt();
  int index = al.indexOf(x);
  if(index == -1) {
   System.out.println("NOT in List");
  }
  else {
   al.remove(index);
   System.out.println("Now List: "+al);
  }
 }
 public static void main(String[] a)
  throws Exception
 { 
  Test t = new Test();
  System.out.println("Add in List ");
  t.addElement();
  t.show();
  t.find();
  t.delete();
 } 
}

Expected Output

Add in List
Enter Element: 1
Want to Add[y/n]: y
Enter Element: 2
Want to Add[y/n]: y
Enter Element: 3
Want to Add[y/n]: y
Enter Element: 4
Want to Add[y/n]: y
Enter Element: 5
Want to Add[y/n]: y
Enter Element: 6
Want to Add[y/n]: y
Enter Element: 7
Want to Add[y/n]: y
Enter Element: 8
Want to Add[y/n]: y
Enter Element: 9
Want to Add[y/n]: n
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Size: 9
Element to find: 12
NOT in List
Element to delete: 5
Now List: [1, 2, 3, 4, 6, 7, 8, 9]

Explanation of the Program

  • ArrayList is a part of the Java Collections Framework. It implements the List interface and provides a dynamic, resizable array.
  • Unlike standard Java arrays (which have a fixed size upon creation), an ArrayList automatically grows its internal capacity when you add elements, and shrinks when you remove them.
  • The indexOf() method is a convenient built-in Linear Search that returns -1 if the element is not found.

Complexity

Time Complexity O(n) - For searching and shifting elements during removal.
Space Complexity O(n)
ADVERTISEMENT