import java.util.ArrayList; public class RemoveElementFromArrayListExample { public static void main(String[] args) { // create an ArrayList object ArrayList arrayList = new ArrayList(); // Appends the specified element to the end of this list arrayList.add("1"); arrayList.add("2"); arrayList.add("3"); System.out.println("ArrayList contains..."); // display elements of ArrayList for (int index = 0; index < arrayList.size(); index++) System.out.println(arrayList.get(index)); /* * 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("Modified ArrayList contains..."); // display elements of ArrayList for (int index = 0; index < arrayList.size(); index++) System.out.println(arrayList.get(index)); } }
The output is:
ArrayList contains...
1
2
3
2 is removed from ArrayList
Modified ArrayList contains...
1
3
No comments:
Post a Comment