Friday, November 11, 2011

Can we replace a value in List? (or ) How to replace a value in List?

Yes, we can replace a value in List using set method's in List (index based) and ListIterator(no index).
and here is code for it.

Sample :


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;

public class ListUtils {
      public static void main(String[] args) {
            // Example 1 : Common List
            List cl = new ArrayList();
            for (int i = 0; i < 10; i++) {
                  cl.add(i);
            }
            cl.set(2, "Replaced");
            System.out.println(cl);

            // Example 2 : Checking on list that's created using Arrays asList
            // method.
            List ls = Arrays.asList(new String[] { "a", "b", "c", "d" });
            ls.set(2, "This is also working.");
            System.out.println(ls);

            // Example 3 : Using List Iterator
            ListIterator lis = ls.listIterator();
            lis.next();
            lis.set("Oh! This is also working.");
            System.out.println(ls);
      }
}


Output :

[0, 1, Replaced, 3, 4, 5, 6, 7, 8, 9]
[a, b, This is also working., d]
[Oh! This is also working., b, This is also working., d]

Note : I have added Example 2 for reference because generally we will think that, we cann't modify the list which is created using Arrays. But that is wrong.

No comments:

Post a Comment