Press "Enter" to skip to content

LinkedList get() method with example in java

The get(int index) method of LinkedList returns the element at the specified index in this list. It throws IndexOutOfBoundsException if the specified index is out of range. (index < 0 || index >= size())

Syntax

Object get(int index)

Parameters

index is the position of the element need to return

Return Value

the element at the specified index

Exception

throws IndexOutOfBoundsException the specified index is out of range

Program 1

import java.util.LinkedList;

public class LinkedListGetExample {

	public static void main(String[] args) {

		LinkedList<Integer> oddNumbers = new LinkedList<>();
		oddNumbers.add(5);
		oddNumbers.add(7);
		oddNumbers.add(9);
		oddNumbers.add(11);

		System.out.println("Linked List elements: " + oddNumbers);
		System.out.println("Element at index 1 in this linked-list: " + oddNumbers.get(1));

		System.out.println("Element at index 3 in this linked-list: " + oddNumbers.get(3));

	}
}

Output

Linked List elements: [5, 7, 9, 11]
Element at index 1 in this linked-list: 7
Element at index 3 in this linked-list: 11

Program 2

import java.util.LinkedList;

public class LinkedListGetExample {

	public static void main(String[] args) {

		LinkedList<Integer> oddNumbers = new LinkedList<>();
		oddNumbers.add(5);
		oddNumbers.add(7);
		oddNumbers.add(9);
		oddNumbers.add(11);

		System.out.println("Linked List elements: " + oddNumbers);
		System.out.println("Element at index 7 in this linked-list: " + oddNumbers.get(7));

	}
}

Output

Linked List elements: [5, 7, 9, 11]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 7, Size: 4
	at java.util.LinkedList.checkElementIndex(LinkedList.java:555)
	at java.util.LinkedList.get(LinkedList.java:476)
	at LinkedListGetExample.main(LinkedListGetExample.java:17)

Be First to Comment

Leave a Reply

Your email address will not be published.