I want to convert String array to ArrayList. For example String array is like:
String[] words = new String[]{"ace","boom","crew","dog","eon"};
How to convert this String array to ArrayList?
I want to convert String array to ArrayList. For example String array is like:
String[] words = new String[]{"ace","boom","crew","dog","eon"};
How to convert this String array to ArrayList?
Use this code for that,
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);
}
}
}
List<String> wordList = Arrays.asList(words); . Is this correct?words is an array of strings, then, yes.new ArrayList( Arrays.asList( new String[]{"abc", "def"} ) );
Arrays.asList return a java.util.Arrays.ArrayList.ArrayList<T>(T[]) so if you try to add something you'll get a java.lang.UnsupportedOperationExceptionnew ArrayList<>(...) worked for me as opposed to new ArrayList(...) (note the <>).List<String> wordList = Arrays.asList(words);, doing wordList instanceof ArrayList<String> will return false.Using 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, but not an ArrayList.in most cases the List<String> should be enough. No need to create an 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);