Arrays.asList() doubt?

前端 未结 8 1278
粉色の甜心
粉色の甜心 2020-12-05 08:00

People say that asList method convert the array into list and its not copying, so every change in \'aList\' will reflect into \'a\'. So add new values in \'aLis

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 08:49

    Manoj,

    The Return type of Arrays.List is some unknown internal implementation of the List interface and not java.util.ArrayList, so you can assign it only to a List type.

    If you assign it to an ArrayList for instance it will give you compile time error "Type mismatch: cannot convert from List to ArrayList"

      ArrayList aList =  Arrays.asList(a);// gives Compile time error
    

    From the Javadoc "Arrays.asList Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) " that means that you are only provided a list view of the Array which IMO is created at runtime and ofcourse you cannot change the size of an array so you can't change size of "Arrays.asList" also.

    IMO the internal implementation of Arrays.asList has all the implemented methods which can change the size of the Array as -

    void add(E e)
    {
    //some unknown code
    throw(java.lang.UnsupportedOperationException);
    }
    

    so whenever you attempt to alter the size of the Array it throws the UnsupportedOperationException.

    Still if you want to add some new items to an ArrayList by using such a syntax, you can do so by creating a subclass of Arraylist(preferably by using anonymous subclass of ArrayList). You can pass the return type of Arrays.List to the constructor of ArrayList, (ie. public ArrayList(Collection c)) something like this -

    List girlFriends = new java.util.ArrayList(Arrays.asList("Rose", "Leena", "Kim", "Tina"));
    girlFriends.add("Sarah");
    

    Now you can easily add Sarah to your GF list using the same syntax.

    PS - Please select this one or another one as your answer because evrything has been explained. Your low Acceptance rate is very discouraging.

提交回复
热议问题