简体   繁体   English

向ArrayList添加Null时出现UnsupportedOperationException

[英]UnsupportedOperationException When Adding Null to ArrayList

I am trying to add null elements to an ArrayList. 我试图将空元素添加到ArrayList。 This is for the purpose of ignoring columns using supercsv: http://supercsv.sourceforge.net/examples_partial_reading.html I am processing multiple csv files which have different number of header columns. 这是出于使用supercsv忽略列的目的: http ://supercsv.sourceforge.net/examples_partial_reading.html我正在处理多个csv文件,这些文件的标头列数不同。

csvBeanReader.getHeader(true) returns String[]. csvBeanReader.getHeader(true)返回String []。 The line headers.add(null); 行headers.add(null); is throwing an UnsupportedOperationException. 引发UnsupportedOperationException。 Why? 为什么? What did I do wrong? 我做错了什么?

List<String> headers = Arrays.asList(csvBeanReader.getHeader(true));

//add null columns to headers
for(int i=0; i<1000; i++){
    headers.add(null);
}

You don't have a java.util.ArrayList , you have something that implements List . 您没有java.util.ArrayList ,但有一些实现List东西。 This particular List implementation doesn't support modification via changing the size of the List . 这个特定的List实现不支持通过更改List的大小进行修改。 Even if you add an actual String , you will still get UnsupportedOperationException . 即使您add了实际的String ,您仍然会得到UnsupportedOperationException From Arrays.asList javadocs : Arrays.asList javadocs

Returns a fixed-size list backed by the specified array. 返回由指定数组支持的固定大小的列表。

To be able to add to that List , wrap it in an actual ArrayList . 为了能够添加到该List ,请将其包装在实际的ArrayList

List<String> headers = new ArrayList<>(Arrays.asList(csvBeanReader.getHeader(true)));

This is because Arrays.asList returns an immutable list. 这是因为Arrays.asList返回一个不可变的列表。

http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...) http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T ...)

An immutable list will throw an exception when a modification is attempted. 尝试进行修改时,不可变列表将引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM