Declare an array, Converting an array to list and create ArrayList (ArrayList) from array (T[]) in Java

Declare an Array in Java

You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).

For primitive types:

int[] myIntArray = new int[3];
int[] myIntArray = {1,2,3};
int[] myIntArray = new int[]{1,2,3};

For classes, for example String, it's the same:

String[] myStringArray = new String[3];
String[] myStringArray = {"a","b","c"};
String[] myStringArray = new String[]{"a","b","c"};

Converting an array to list in Java

Integer[] spam = new Integer[] { 1, 2, 3 };


ArrayList<String> stock_list = new ArrayList<String>();
String[] stockArr = new String[stock_list.size()];
stockArr = stock_list.toArray(stockArr);
for(String s : stockArr)

Create ArrayList (ArrayList<T>) from array (T[]) in Java

new ArrayList<Element>(Arrays.asList(array))


Element[] array = new Element[] { new Element(1),new Element(2),new Element(3) };

The simplest answer is to do:

List<Element> list = Arrays.asList(array);

Happy Coding!!!

No comments:

Post a Comment


Most recent Elastic Search tutorials for beginner, intermediate and advance level developer, Yubraj Pokharel, in CodingWorkspace