Sunday, 25 May 2014

LinkedList : set : Replace value at particular index

public E set(int index, E element)
Replaces the element at the specified position in this list with the specified element.

import java.util.*;

class LinkedListSet{
 public static void main(String args[]){
  LinkedList<Integer> myList;
  myList = new LinkedList<> ();
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(20);
  myList.add(30);
  myList.add(40);
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  System.out.println("\nReplace 10 by 50");
  myList.set(0, 50);
  
  System.out.println("\nElements in myList are");
  System.out.println(myList);
 }
}

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

Replace 10 by 50

Elements in myList are
[50, 20, 30, 40]

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

class LinkedListSetIndexOut{
 public static void main(String args[]){
  LinkedList<Integer> myList;
  myList = new LinkedList<> ();
  
  /* Add Elements to myList */
  myList.add(10);
  myList.add(20);
  myList.add(30);
  myList.add(40);
  
  System.out.println("Elements in myList are");
  System.out.println(myList);
  
  System.out.println("\nReplace Element at index 5 by 50");
  myList.set(5, 50);
  
  System.out.println("\nElements in myList are");
  System.out.println(myList);
 }
}

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

Replace Element at index 5 by 50
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size:4
        at java.util.LinkedList.checkElementIndex(LinkedList.java:553)
        at java.util.LinkedList.set(LinkedList.java:488)
        at LinkedListSetIndexOut.main(LinkedListSetIndexOut.java:18)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment