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]
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!