简体   繁体   中英

UnsupportedOperationException When Adding Null to ArrayList

I am trying to add null elements to an 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.

csvBeanReader.getHeader(true) returns String[]. The line headers.add(null); is throwing an 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 . This particular List implementation doesn't support modification via changing the size of the List . Even if you add an actual String , you will still get UnsupportedOperationException . From 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<String> headers = new ArrayList<>(Arrays.asList(csvBeanReader.getHeader(true)));

This is because Arrays.asList returns an immutable list.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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