Java LinkedList get(int index) Method Example

We have already seen that the element() method of java.util.LinkedList class will get you the head of the list whereas  get(int index) method will return the element which is present at the mentioned index.

Signature

public E get(int index) 

Retrieves the element which is present at the particular index of the list and will throw “IndexOutOfBoundsException” if the index is not within the range

Example

The following example shows the usage of get(index) method.

import java.util.LinkedList;

public class GetMethodLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList list1 = new LinkedList();
		
		// use add() method to add elements to the LinkedList
		list1.add("Element1");
		list1.add("Element2");
		list1.add("Element3");
		
		//Getting element at a praticular index
		System.out.println("Element at index 1 is : "+list1.get(1));
		
	}
}

Output

Element at index 1 is : Element2

Leave a Reply

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