您的位置:首页 > 其它

Arrays.asList()返回只读的List

2016-01-15 15:05 330 查看
List<Integer> list = Arrays.asList(1, 2, 3);

list.clear(); // throws java.lang.UnsupportedOperationException

对Arrays.asList()转化的List是一个固定长度的List,不支持add() remove() clear()等操作

[b]Arrays.asList()返回的是一个ArrayList对象[/b]



@SafeVarargs

@SuppressWarnings("varargs")

public static <T> List<T> asList(T... a) {

return new ArrayList<>(a);

}
而这个类继承自AbstractList类

在AbstractList中而这个类中实现的所有对list的数据编辑操作都会抛出UnsupportedOperationException异常

/**

* {@inheritDoc}

*

* <p>This implementation always throws an

* {@code UnsupportedOperationException}.

*

* @throws UnsupportedOperationException {@inheritDoc}

* @throws ClassCastException {@inheritDoc}

* @throws NullPointerException {@inheritDoc}

* @throws IllegalArgumentException {@inheritDoc}

* @throws IndexOutOfBoundsException {@inheritDoc}

*/

public E set(int index, E element) {

throw new UnsupportedOperationException();

}

/**

* {@inheritDoc}

*

* <p>This implementation always throws an

* {@code UnsupportedOperationException}.

*

* @throws UnsupportedOperationException {@inheritDoc}

* @throws ClassCastException {@inheritDoc}

* @throws NullPointerException {@inheritDoc}

* @throws IllegalArgumentException {@inheritDoc}

* @throws IndexOutOfBoundsException {@inheritDoc}

*/

public void add(int index, E element) {

throw new UnsupportedOperationException();

}

/**

* {@inheritDoc}

*

* <p>This implementation always throws an

* {@code UnsupportedOperationException}.

*

* @throws UnsupportedOperationException {@inheritDoc}

* @throws IndexOutOfBoundsException {@inheritDoc}

*/

public E remove(int index) {

throw new UnsupportedOperationException();

}

所以Arrays.asList()返回的list是只读的并不能对list的数据进行相关修改!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: