Convert Java Array To List

This article will show you how to convert Java Array to List. There are two method in below java code. One method convert a Java String Array to String List, the other convert Java Object Array to Object List.

public class JavaArrayToListConverter {

	public static void main(String[] args) {

		/* Declare and initiate a String array. */
		String strArr[] = {"TestNG", "Selenium", "WebDriver", "Hibernate", "Spring"};
	/* Convert a String array to an editable list. */
	private static List<String> stringArrayToList(String strArr[])
		/* Declare return object. */
		List<String> retObj = new ArrayList<String>();
			/* This method will covert the array to a not editable list which can not add or delete item because the list's length is fixed. */
			retObj = Arrays.asList(strArr);
			/* So below method will throw a java.lang.UnsupportedOperationException exception. 
			/* Create a new editable list. */
			List<String> retList = new ArrayList<String>();
			/* Add all items in retObj (not editable) to retList (editable).*/
			/* Point retObj to the retList. */
			retObj = retList;
			/* Now can add element in retObj. */
			/* Add element at specified index. */
			retObj.add(2, "Sql Server");
			/* Loop in retObj.*/
			int size = retObj.size();
			for(int i=0;i<size;i++)
				String str = retObj.get(i);
				/* Print out each item. */
		return retObj;
	/* Convert an Object array to Object list. */
	private static List<Object> objArrayToList(Object objArr[])
		/* Declare return object. */
		List<Object> ret = new ArrayList<Object>();
			/* Get objArr size. */
			int objArrSize = objArr.length;
			/* Loop in the array, add each item to ret. */
			for(int i=0;i<objArrSize;i++)
			/* ret is editable. So can add item to it. */
			/* Add String at specified index. */
			ret.add(2, "Lucent");
			/* Loop in ret.*/
			int size = ret.size();
			for(int i=0;i<size;i++)
				Object obj = ret.get(i);
				/* Print out each item's value. */
		return ret;

[download id=”1804″]

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.