Sunday, 11 May 2014

LinkedList : get : Get the Element at Specific index

public E get(int index)
Returns the element at the specified position in this list.

import java.util.*;

class LinkedListGet{
  public static void main(String args[]){
    LinkedList<Integer> myList;
    myList = new LinkedList<Integer> ();
  
    /* Add Elements to myList */
    myList.add(10);
    myList.add(20);
    myList.add(30);
    myList.add(40);
  
    System.out.println("Elements in myList are " + myList);
    System.out.println("\nElement at index 1 is " + myList.get(1));
  }
}

Output
Elements in myList are [10, 20, 30, 40]

Element at index 1 is 20

1. Throws IndexOutOfBoundsException, if index is out of range
import java.util.*;

class LinkedListGetIndexOut{
  public static void main(String args[]){
    LinkedList<Integer> myList;
    myList = new LinkedList<Integer> ();
  
    /* Add Elements to myList */
    myList.add(10);
    myList.add(20);
    myList.add(30);
    myList.add(40);
  
    System.out.println("Elements in myList are " + myList);
    System.out.println("\nElement at index -1 is " + myList.get(-1));
  }
}

Output
Elements in myList are [10, 20, 30, 40]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: -1, Size: 4
        at java.util.LinkedList.checkElementIndex(LinkedList.java:553)
        at java.util.LinkedList.get(LinkedList.java:474)
        at LinkedListGetIndexOut.main(LinkedListGetIndexOut.java:15)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment