将string数组转换为ArrayList
可能重复:
在Java中将数组转换为列表
我想将String
数组转换为ArrayList
。 例如,string数组是这样的:
String[] words = new String[]{"ace","boom","crew","dog","eon"};
如何将此string数组转换为ArrayList?
使用这个代码,
import java.util.Arrays; import java.util.List; import java.util.ArrayList; public class StringArrayTest { public static void main(String[] args) { String[] words = {"ace", "boom", "crew", "dog", "eon"}; List<String> wordList = Arrays.asList(words); for (String e : wordList) { System.out.println(e); } } }
new ArrayList( Arrays.asList( new String[]{"abc", "def"} ) );
使用Collections#addAll()
String[] words = {"ace","boom","crew","dog","eon"}; List<String> arrayList = new ArrayList<>(); Collections.addAll(arrayList, words);
String[] words= new String[]{"ace","boom","crew","dog","eon"}; List<String> wordList = Arrays.asList(words);
在大多数情况下, List<String>
应该足够了。 不需要创build一个ArrayList
import java.util.ArrayList; import java.util.Arrays; import java.util.List;
…
String[] words={"ace","boom","crew","dog","eon"}; List<String> l = Arrays.<String>asList(words); // if List<String> isnt specific enough: ArrayList<String> al = new ArrayList<String>(l);