Solution of java.lang.UnsupportedOperationException

wrong code

private List<String> mImgs;

mImgs = Arrays.asList(mOriginSImgs);

mImgs.remove(i);//这里报错

Running exception: java.lang.UnsupportedOperationException

The problem occurs for the following reasons:

1. There are two packages in the text class: a, java.util.ArrayList package; b, java.util.Arrays.ArrayList package (emphasis)

2. Calling the add and remove methods of the List produced by Arrays.asList() reports an exception. This is because Arrays.asList() returns the internal class ArrayList of Arrays, not java.util.ArrayList.

3. Using the asList method to inherit the add and remove of the parent class will only throw an UnsupportedOperationException exception, and java.util.ArrayList rewrites the add and remove of the parent class

4. Therefore, ArrayList is required to use the add() method correctly.

Solution:

mImgs.addAll(Arrays.asList(mOriginSImgs));

 

Summarize:


This error comes from an interview question my teacher shared with him;

The knowledge point is to use the add and remove of the parent class inherited by the asList method, which will only throw an UnsupportedOperationException exception. java.util.ArrayList rewrites the add and remove of the parent class, so ArrayList is needed to call the method

Reference: Solutions to java.lang.UnsupportedOperationException_Gu Wanning's Blog-CSDN Blog

Guess you like

Origin blog.csdn.net/fromVillageCoolBoy/article/details/131112107