调用list.remove(0)时出现Strange UnsupportedOperationException [英] Strange UnsupportedOperationException when calling list.remove(0)

查看:131
本文介绍了调用list.remove(0)时出现Strange UnsupportedOperationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个方法,它接受字符串的变量,从中创建一个List,然后尝试删除列表的第一个元素。

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
}

但是只要删除被调用,抛出 UnsupportedOperationException 。我的猜测是返回List-Type不支持remove方法。我对么?我有哪些替代方案?

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?

推荐答案

Arrays.asList 仅提供数组周围的薄包装。此包装器允许您使用 List API对阵列执行大多数操作。来自JavaDoc的引用:

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:


返回由指定数组支持的固定大小列表。 [...]
此方法充当基于数组和基于集合的API之间的桥梁[...]

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));

这个创建一个真正的 ArrayList (其中支持 remove )并用另一个列表的内容填充它,该列表恰好是 String [] 的包装器。

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[].

这篇关于调用list.remove(0)时出现Strange UnsupportedOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆