Sunday 1 June 2014

ArrayList : 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 ArrayListSet{
 public static void main(String args[]){
  ArrayList<Integer> myList;
  myList = new ArrayList<> ();
  
  /* 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 ArrayListSetIndexOut{
 public static void main(String args[]){
  ArrayList<Integer> myList;
  myList = new ArrayList<> ();
  
  /* 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.ArrayList.rangeCheck(ArrayList.java:638)
        at java.util.ArrayList.set(ArrayList.java:429)
        at ArrayListSetIndexOut.main(ArrayListSetIndexOut.java:18)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment