1.Basic java Example program to remove an element from specified index ArrayList.
Output:
2.Basic java Example program to remove all elements from ArrayList.
Output:
- package com.instanceofjavaforus;
- import java.util.ArrayList;
- public class RemoveElementArrayList{
- public static void main(String[] args) {
- //create an ArrayList object
- ArrayList<String> arrayList = new ArrayList<String>();
- //Add elements to Arraylist
- arrayList.add("A");
- arrayList.add("B");
- arrayList.add("C");
- arrayList.add("A");
- /*
- To remove an element from the specified index of ArrayList use
- Object remove(int index) method.
- It returns the element that was removed from the ArrayList. */
- Object obj = arrayList.remove(1);
- System.out.println(obj + " is removed from ArrayList");
- System.out.println("ArrayList contains...");
- //display ArrayList elements using for loop
- for(int index=0; index < arrayList.size(); index++)
- System.out.println(arrayList.get(index));
- }
- }
Output:
- B is removed from ArrayList
- ArrayList contains...
- A
- C
- A
- package com.instanceofjavaforus;
- import java.util.ArrayList;
- public class RemoveAllElementArrayList{
- public static void main(String[] args) {
- //create an ArrayList object
- ArrayList<String> arrayList = new ArrayList<String>();
- //Add elements to Arraylist
- arrayList.add("A");
- arrayList.add("B");
- arrayList.add("C");
- arrayList.add("A");
- System.out.println("Size of ArrayList before removing elements : "+ arrayList.size());
- /*
- To remove all elements from the ArrayList we need to use
- void clear() method.
- */
- arrayList.clear();
- System.out.println("Size of ArrayList after removing elements : "+ arrayList.size());
- }
- }
- B is removed from ArrayList
- ArrayList contains...
- A
- C
- A
No comments