Thursday 29 November 2012

Remove an element from specified index of Java ArrayList Example

Leave a Comment
  1. import java.util.ArrayList;
  2.  
  3. public class RemoveElementFromArrayListExample {
  4.  
  5.   public static void main(String[] args) {
  6.     //create an ArrayList object
  7.     ArrayList arrayList = new ArrayList();
  8.    
  9.     //Add elements to Arraylist
  10.     arrayList.add("1");
  11.     arrayList.add("2");
  12.     arrayList.add("3");
  13.    
  14.     /*
  15.       To remove an element from the specified index of ArrayList use
  16.       Object remove(int index) method.
  17.       It returns the element that was removed from the ArrayList.
  18.     */
  19.     Object obj = arrayList.remove(1);
  20.     System.out.println(obj + " is removed from ArrayList");
  21.    
  22.     System.out.println("ArrayList contains...");
  23.     //display elements of ArrayList
  24.     for(int index=0; index < arrayList.size(); index++)
  25.       System.out.println(arrayList.get(index));
  26.    
  27.   }
  28. }

0 comments:

Post a Comment