Tuesday 1 April 2014

get : Get ArrayList Item by using Index

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

import java.util.*;

class ListGetByIndex{
 public static void main(String args[]){
  List<Integer> myList = new LinkedList<> ();
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(13);
  myList.add(100);
  myList.add(95);
  myList.add(123);
  
  System.out.println("Elements in the List are");
  System.out.println(myList+"\n");
  
  for(int i = 0; i < myList.size(); i++){
   System.out.println("Index " + i + " has " + myList.get(i));
  } 
 }
}

Output
Elements in the List are
[10, 13, 100, 95, 123]

Index 0 has 10
Index 1 has 13
Index 2 has 100
Index 3 has 95
Index 4 has 123

1. throws IndexOutOfBoundsException if the index is out of range

import java.util.*;

class ListGetIndexOut{
 public static void main(String args[]){
  List<Integer> myList = new LinkedList<> ();
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(13);
  myList.add(100);
  myList.add(95);
  myList.add(123);
  
  System.out.println("Elements in the List are");
  System.out.println(myList+"\n");
  
  /* Trying to access the element which is out of index */
  myList.get(5);
 }
}

Output
Elements in the List are
[10, 13, 100, 95, 123]

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size:5
        at java.util.LinkedList.checkElementIndex(Unknown Source)
        at java.util.LinkedList.get(Unknown Source)
        at ListGetIndexOut.main(ListGetIndexOut.java:18)





Prevoius                                                 Next                                                 Home

No comments:

Post a Comment