Strange UnsupportedOperationException when calling list.remove(0)

后端 未结 5 1470
故里飘歌
故里飘歌 2021-01-23 17:04

I have this method which takes a varargs of Strings, creates a List out of it, and then tries to remove the first element of the list.

public void importFrom(Str         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-23 17:44

    Arrays.asList only provides a thin wrapper around an array. This wrapper allows you to do most operations on an array using the List API. A quote from the JavaDoc:

    Returns a fixed-size list backed by the specified array. [...] This method acts as bridge between array-based and collection-based APIs [...]

    If you really want to remove something, then this might work:

    List realList = new ArrayList(Arrays.asList(stringArray));
    

    This one creates a real ArrayList (which supports remove) and fills it with the contents of another list which happens to be the wrapper around your String[].

提交回复
热议问题