1.Basic java Example program to remove an element from specified index ArrayList.

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


Output:

  1. B is removed from ArrayList
  2. ArrayList contains...
  3. A
  4. C
  5. A

     
 2.Basic java Example program to remove all elements from ArrayList.

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  
  4. public class RemoveAllElementArrayList{
  5.  
  6. public static void main(String[] args) {
  7.  
  8.    //create an ArrayList object
  9.         ArrayList<String> arrayList = new ArrayList<String>();
  10.        
  11.         //Add elements to Arraylist
  12.         arrayList.add("A");
  13.         arrayList.add("B");
  14.         arrayList.add("C"); 
  15.         arrayList.add("A");
  16.        
  17.  
  18. System.out.println("Size of ArrayList before removing elements : "+ arrayList.size());
  19.  
  20. /*
  21. To remove all elements from the ArrayList we need to use
  22. void clear() method.
  23. */
  24. arrayList.clear();
  25. System.out.println("Size of ArrayList after removing elements : "+ arrayList.size());  
  26.  
  27.  }
  28. }
     
Output:

     
  1. B is removed from ArrayList
  2. ArrayList contains...
  3. A
  4. C
  5. A

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu