Precautions for using Arrays. asList

Source: Internet
Author: User
1. Blog category:
2 java Integration
3. data structures and algorithms
4
5 Arrays. asList
6
7. Check the following code:
8. Add Java code to favorites
9
10 import java. util. Arrays;
11 import java. util. List;
12
13
14 public class TestAsList {
15
16 public static void main (String [] args ){
17 String [] str = new String [] {"1", "2", "3 "};
18 List <String> list = Arrays. asList (str );
19 list. add ("4 ");
20}
21}
22
23
24
25 you guess, is there a problem?
26
27. Run the program and report a future error:
28 Java code favorites code
29
30 Exception in thread "main" java. lang. UnsupportedOperationException
31 at java. util. AbstractList. add (AbstractList. java: 131)
32 at java. util. AbstractList. add (AbstractList. java: 91)
33 at test. TestAsList. main (TestAsList. java: 12)
34
35
36
37 Cause Analysis:
38
39 The value of list is transmitted from data, so the length of list is fixed. An error occurred while running the program to list. add ("4.
40
41. solution:
42 Java code collection code
43
44 import java. util. ArrayList;
45 import java. util. Arrays;
46 import java. util. List;
47
48
49 public class TestAsList {
50
51 public static void main (String [] args ){
52 String [] str = new String [] {"1", "2", "3 "};
53 List <String> list = new ArrayList <String> (Arrays. asList (str ));
54 list. add ("4 ");
55 System. out. println (list. size ());
56}
57}
58
59
60
61. Conclusion: Pay attention when using asList.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.