LinkedList get() method with example in java

Published by user on

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 = 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 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 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)
Categories: Java

0 Comments

Leave a Reply

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