Strange UnsupportedOperationException when calling list.remove(0)

我的梦境 提交于 2019-12-31 04:50:08

问题


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(String... files) {
    List<String> fileList = Arrays.asList(files);

    String first = fileList.remove(0);
    // other stuff
}

But as soon as remove gets called, an UnsupportedOperationException is thrown. My guess is that the return List-Type does not support the remove method. Am I correct? What alternatives do I have?


回答1:


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<String> realList = new ArrayList<String>(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[].




回答2:


Arrays.asList provides a List view of the array, BACKED by the array. And arrays are not resizable. Any attempt to change its size will throw an exception.




回答3:


You could just create a new ArrayList<String>(), then loop over all files for (String file : files) fileList.add(file);. Or you could use the List you already created and add it to the new ArrayList using fileList.addAll(files);




回答4:


Arrays.asList() returns instance of Arrays.ArrayList that that is unmodifireable list because it is a simple wrapper over array. You cannot remove elements from array.

This is written in javadoc of asList():

Returns a fixed-size list backed by the specified array.




回答5:


The returned list acts as a view for the backed array. You can not modify the list directly but only through the backed array. However, you cannot resize the array.



来源:https://stackoverflow.com/questions/7952462/strange-unsupportedoperationexception-when-calling-list-remove0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!