You can convert arrays to Lists and Lists to arrays.
[wp_ad_camp_1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | package arraytolist; import java.util.Arrays; import java.util.List; public class ArrayToListAndBack { public static void main(String[] args) { String[] names = { "Karl", "Peter", "Lucas" }; // Array to list List<String> listNames = Arrays.asList(names); // List to array String[] newArrayNames = listNames.toArray(new String[0]); for (String t : newArrayNames) { System.out.println(t); } } } |
Line 11 specifies the type of the array. The advantage of specifying a size of 0 for the parameter is that Java will create a new array of the proper size for the return value. You can suggest a larger array to be used instead. If the ArrayList
fits in the array, it will be returned. Otherwise, a new one will be created.
[wp_ad_camp_2]