1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Arrays; /* Java String Array To List Example This Java String Array To List Example shows how to convert Java String array to java.util.List object using Arrays.asList method. */ public class JavaStringArrayToListExample { public static void main(String args[]){ //create String array String[] numbers = new String[]{"one", "two", "three"}; /* * To covert String array to java.util.List object, use * List asList(String[] strArray) method of Arrays class. */ List list = (List) Arrays.asList(numbers); //display elements of List System.out.println("String array converted to List"); for(int i=0; i < list.size(); i++){ System.out.println(list.get(i)); } /* * Please note that list object created this way can not be modified. * Any attempt to call add or delete method would throw UnsupportedOperationException exception. * * If you want modifiable list object, then use * * ArrayList list = (ArrayList) Arrays.asList(numbers); */ /* Alternate Method to covert String array to List */ List anotherList = new ArrayList(); Collections.addAll(anotherList, numbers); } } /* Output of this example would be String array converted to List one two three */ |
Add Comment