当前位置:网站首页>Unsupportedoperationexception exception resolution

Unsupportedoperationexception exception resolution

2022-06-09 10:19:00 11 brother sun

Yige In the course of teaching , It often makes people think about how to make themselves become an experienced development God . I think one way to become a great God is , Develop good study habits , For example, record every problem encountered in the learning and development process .

One . bug repeat

see , lately Yige One of my students was writing code , Use Arrays.asList() The utility class wants to convert an array into a collection , Then he wants to add new elements to the set of array transformations , The result is inexplicably thrown
UnsupportedOperationException abnormal , How did this happen ? So I recorded the cause of the exception and the solution process , For your reference to develop their own learning habits .

The core code is as follows :

public static void main(String[] args) {
 // 1  Build the original array 
 String[] strArray = new String[] { "i", "love" };
 // 2  adopt Arrays.asList  The tool converts an array into List  aggregate 
 List<String> strList = Arrays.asList(strArray);
 // 3  Add elements to a collection 
 strList.add("you");
}

The operation results are as follows :

Two . bug Cause analysis

Just a few lines of code , Such an exception should have occurred , As a student, my mentality is a bit broken . How did the above exception come about ?

We turn on Arrays.asList() Method source code , It can be found from the source code : asList() The return value of the method is a Arrays Inner class --ArrayList, This class does not implement List How to modify a collection ,Arrays.asList() The adapter mode is adopted , Just switched the interface , The data structure in the background is still an array , So we can't directly use asList() Method to add or modify the returned collection !

 

3、 ... and . Exception resolution

therefore , After analyzing the source code, we can find a solution , That is, you just need to convert the array into a set , adopt ArrayList Construction method of , Constructing a new set can solve this problem perfectly ! The solution code is as follows :

public static void main(String[] args) {
   // 1  Build the original array 
   String[] strArray = new String[] { "i", "love" };
   // 2  adopt Arrays.asList  The tool converts an array into List  aggregate 
   List<String> strList = Arrays.asList(strArray);
   // 3  hold strList  Pack into a new one ArrayList
   List<String> newStrList = new ArrayList<>(strList);
   // 4  Add new elements to the new collection 
   newStrList.add("you");
}

Now you know how this exception came about , How to solve it ? If you have any questions , You can give a comment to Yige Leave a message .

原网站

版权声明
本文为[11 brother sun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090938331052.html