Java LinkedList set(int index,E element) Method Example

The set(int index,E element) method of java.util.LinkedList class will replace the element at the specified index in this list with the specified element.

Signature

public E set(int index,E element)

This method replaces the element of the list at the index with the element which we pass and will throw java.Lang.IndexOutOfBoundsException if the index is out of range.

Example

The following example shows the usage of java.util.LinkedList.set(index,element) method.

import java.util.LinkedList;

public class SetMethodLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList l = new LinkedList();
		
		// use add() method to add elements to the list
		l.add("Element1");
		l.add("Element2");
		l.add("Element3");
		l.add("Element4");
		l.add("Element5");
		
		//Printing the elements of the list
		System.out.println("**Elements of the list before set**");
		for(String temp:l)
		{
			System.out.println(temp);
		}
		
		//replace element at index 1 with "JavaInterviewPoint"
		System.out.println("Element replaced is : \""+l.set(1,"JavaInterviewPoint")+"\"");
		
		//Printing the elements of the list
		System.out.println("**Elements of the list after set**");
		for(String temp:l)
		{
			System.out.println(temp);
		}
	}
}

Output

**Elements of the list before set**
Element1
Element2
Element3
Element4
Element5
Element replaced is : "Element2"
**Elements of the list after set**
Element1
JavaInterviewPoint
Element3
Element4
Element5

Leave a Reply

Your email address will not be published. Required fields are marked *