Thursday 16 October 2014

Arrays.asList method


public static <T> List<T> asList(T... a)
As per Javadoc, this method returns a fixed-size list backed by the specified array.

import java.util.Arrays;
import java.util.List;

public class ArrayasList {
    public static void main(String args[]){
        String arr[] = {"Hi", "How", "Are", "You"};
        List<String> myList = Arrays.asList(arr);

        System.out.println(myList);
    }
}


Output
[Hi, How, Are, You]

Javadoc clearly says the list returned by this method is fixed size, so if you tries to remove or add from/to the list run time throws “UnsupportedOperationException”.

import java.util.Arrays;
import java.util.List;

public class ArrayasList {
    public static void main(String args[]){
        String arr[] = {"Hi", "How", "Are", "You"};
        List<String> myList = Arrays.asList(arr);

        System.out.println(myList);
        myList.remove(1);
    }
}


When you tries to run above program, run time throws “UnsupportedOperationException”.


No comments:

Post a Comment