[Code]Array-> List (stringarraytest. Java)
01 |
import java.util.Arrays;
|
02 |
import java.util.List;
|
03 |
import java.util.ArrayList;
|
05 |
public class StringArrayTest |
07 |
public static
void main(String[] args) |
09 |
String[] words = { "ace" , "boom" ,
"crew" , "dog" ,
"eon" }; |
11 |
List<String> wordList = Arrays.asList(words); |
13 |
for (String e : wordList) |
15 |
System.out.println(e); |
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 = new ArrayList<String>(words.length); |
3 |
for (String s : words) {
|
[Code]This method also works.
1 |
import java.util.Collections;
|
3 |
List myList = new ArrayList(); |
4 |
String[] myStringArray = new String[] { "Java" , "is" ,
"Cool" }; |
6 |
Collections.addAll(myList, myStringArray); |