In the following example we will discuss how can you remove an element at the specified position from a list.
remove (int index) method of List Interface in java
In the following example we will discuss how can you remove an element at the specified position from a list.
Syntax
public Object remove (int index)
It returns the element that was removed from the list.
In this method you can delete a specified element at the specific position into a list. It returns an element at the specified position in terms of Object. After deletion of an element the lists index is reduced by (-1). All the rest elements which are positioned right from previously removed element are shifted left by subtracting (-1) in their indexes in the order they are previously arranged.
Parameter Description
int index : It takes an argument as integer value onto which place (index) do you want to remove an element.
Example of remove (int index) method
In this example we will show you how does remove (int index) method works in List interface. This example will help you to understand how can you remove an element at the specific index position of a list. Through this example we will show you adding of element to the list, show the element with their position, size of list, and deletion of an element at the specified position in a list.
Example:-
package Devmanuals.com; import java.util.List; import java.util.ArrayList; public class ListRemoveIndex { public static void main(String args[]){ ArrayList al = new ArrayList (); al.add("Ram"); al.add("Shyam"); al.add("Ghanshyam"); al.add("Sohan"); al.add("Mohan"); System.out.println("Initial size of list is : "+al.size()); for(int i=0;i<al.size();i++) System.out.println("Element at the position " +i+"=" +al.get(i)); Object obj=al.remove(2); System.out.println("The removed element at position 2 is "+obj); System.out.println("The new list with their index values are : " ); for(int i=0;i<al.size();i++) System.out.println("At position " +i + " element is " +al.get(i)); System.out.println("Size of list after removing element i : "+al.size()); } }
Output :
Initial size of list is : 5 Element at the position 0=Ram Element at the position 1=Shyam Element at the position 2=Ghanshyam Element at the position 3=Sohan Element at the position 4=Mohan The removed element at position 2 is Ghanshyam The new list with their index values are : At position 0 element is Ram At position 1 element is Shyam At position 2 element is Sohan At position 3 element is Mohan Size of list after removing element is : 4 |
[ 0 ] Comments