Convert Java array to list

Source: Internet
Author: User
[Code]Array-> List (stringarraytest. Java)
01 import
java.util.Arrays;
02 import
java.util.List;
03 import
java.util.ArrayList;
04  
05 public
class
StringArrayTest
06 {
07    publicstatic
void main(String[] args)
08    {
09       String[] words = {"ace","boom",
"crew","dog",
"eon"};
10
11       List<String> wordList = Arrays.asList(words);
12
13       for(String e : wordList)
14       {
15          System.out.println(e);
16       }
17    }
18

}

Java. Lang. unsupportedoperationexception occurs when you call add and remove methods after using arrays. aslist. This is because arrays. aslist () returns java. util. arrays $ arraylist instead of arraylist. Both arrays $ arraylist and arraylist inherit the abstractlist, remove, add, and other methods. In abstractlist, the default throw unsupportedoperationexception is thrown and no operation is performed. Arraylist
Override these methods are used to operate the list, but arrays $ arraylist does not include override remove (), add (), and so on, so throw unsupportedoperationexception.

The solution is to use iterator or convert it to arraylist.

List arraylist =
New arraylist (wordlist );

 

[Code]Silly practice
1 String[] words = { ... };
2 List<String> list = newArrayList<String>(words.length);
3 for
(String s : words) {
4     list.add(s);
5 }
[Code]This method also works.
1 import
java.util.Collections;
2  
3 List myList = newArrayList();
4 String[] myStringArray = newString[] {"Java","is",
"Cool"};
5  
6 Collections.addAll(myList, myStringArray);

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.