The set() method of java.util.AbstractList class is used to replace any particular element in the abstract list created using the AbstractList class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() method.
Syntax:
AbstractList.set(int index, Object element)
Parameters: This function accepts two parameters as described below:
- index: This is of integer type and refers to the position of the element that is to be replaced from the abstract list.
- element: It is the new element by which the existing element will be replaced and is of the same object type as the abstract list.
Return Value: The method returns the previous value from the abstract list that is replaced with the new value.
Below program illustrate the AbstractList.set() method:
import java.util.*;
import java.util.LinkedList;
public class AbstractListDemo {
public static void main(String args[])
{
AbstractList<String> list = new LinkedList<String>();
list.add( "Geeks" );
list.add( "for" );
list.add( "Geeks" );
list.add( "10" );
list.add( "20" );
System.out.println( "AbstractList:" + list);
System.out.println( "The Object that is replaced is: "
+ list.set( 2 , "GFG" ));
System.out.println( "The Object that is replaced is: "
+ list.set( 4 , "50" ));
System.out.println( "The new AbstractList is:" + list);
}
}
|
Output:
AbstractList:[Geeks, for, Geeks, 10, 20]
The Object that is replaced is: Geeks
The Object that is replaced is: 20
The new AbstractList is:[Geeks, for, GFG, 10, 50]
Program 2:
import java.util.*;
public class LinkedListDemo {
public static void main(String args[])
{
AbstractList<Integer>
list = new LinkedList<Integer>();
list.add( 10 );
list.add( 20 );
list.add( 30 );
list.add( 40 );
list.add( 50 );
System.out.println( "AbstractList:" + list);
System.out.println( "The Object that is replaced is: "
+ list.set( 0 , 100 ));
System.out.println( "The Object that is replaced is: "
+ list.set( 1 , 200 ));
System.out.println( "The new AbstractList is:" + list);
}
}
|
Output:
AbstractList:[10, 20, 30, 40, 50]
The Object that is replaced is: 10
The Object that is replaced is: 20
The new AbstractList is:[100, 200, 30, 40, 50]
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
26 Nov, 2018
Like Article
Save Article