TomRed.net

  • Increase font size
  • Default font size
  • Decrease font size
Subscribe Bookmark and Share
Home Tutorials CSS Java Convert an array to a list or a list to an array

Java Convert an array to a list or a list to an array

User Rating: / 0
PoorBest 

It is a simple process to convert an array to a list or vice-versa.

Convert an array to a list

In the example below I have used which is generics and is not a necessary part of the code but is good coding practice. the value between the is the object type ie String, Date, MyObject etc.
Arrays is a java.util.Arrays object.

List stringList = Arrays.asList(stringArray);

Lists can also be created on the dynamically in the following way.

List stringList = Arrays.asList(new String[]{"aString", "someText", astringVariable});

Convert a list into an array

List is an interface java.util.List. Lists provide a useful toArray() method which can used to covert the list to an array as in the example below.

String[] stringArray = stringList.toArray();

As above you can also supply an array to the toArray method of the list interface (although what benefit this provides is not clear in this example).

String[] stringArray = stringList.toArray(new String[]{});