ArrayList example

ArrayList example
 package com.ram;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {
 public static void main(String[] args) {
  //Create an ArrayList
  ArrayList<String> al = new ArrayList<String>();
  
  al.add("Coke");
  al.add("Pepsi");
  al.add("Sprite");
  al.add("Mountain Dew");
  al.add("Fanta");
  al.add("Red Bull");
  
  //Get the size of ArrayList
  System.out.println("Size of ArrayList: "+al.size());
  
  //Display elements of ArrayList
  System.out.println("ArrayList elements: "+al);
  
  //Retrieve an element using its index
  System.out.println(al.get(5));
  
  //Replace an element at the specified position in the list with the specified element
  al.set(0, "Coca-cola coke");
  System.out.println("ArrayList elements: "+al);
  
  //Inserts an element at the specified location.
  al.add(2, "ThumsUp");
  System.out.println("ArrayList elements: "+al);
  
  //Checks if the element "Fanta" is in the list. If present will return true else false.
  System.out.println(al.contains("Fanta"));
  
  System.out.println(al.remove("Fanta"));
  
  //Display ArrayList elements using iterator
  Iterator<String> it = al.iterator();
  while(it.hasNext()){
   System.out.println(it.next());
  }
  
  //Removes all elements from the list
  al.clear();
  System.out.println("Size of ArrayList: "+al.size());
 }
}

 
Execute ArrayListExample class and you get the below output:
Size of ArrayList: 6
ArrayList elements: [Coke, Pepsi, Sprite, Mountain Dew, Fanta, Red Bull]
Red Bull
ArrayList elements: [Coca-cola coke, Pepsi, Sprite, Mountain Dew, Fanta, Red Bull]
ArrayList elements: [Coca-cola coke, Pepsi, ThumsUp, Sprite, Mountain Dew, Fanta, Red Bull]
true
true
Coca-cola coke
Pepsi
ThumsUp
Sprite
Mountain Dew
Red Bull
Size of ArrayList: 0

No comments:

Post a Comment