1. 程式人生 > >java實現String[]和List相互轉換

java實現String[]和List相互轉換

場景:
    java實現String[]和List相互轉換封裝
1.List轉換為String[]

        /**1.將list轉換為陣列*/
	public static String[] convertListToStringArray(List list) {
		String[] array = null;
		if ((list != null) && (list.size() > 0)) {
			int length = list.size();
			array = new String[length];
			for (int i = 0; i < length; i++) {
				array[i] = (String) list.get(i);
			}
		}
		return array;
	}

2.String[]轉換為List

        /**2.將陣列轉換為list*/
	public static List convertStringArrayToList(String[] array) {
		List list = null;
		if (array != null) {
			int length = array.length;
			list = new ArrayList();
			for (int i = 0; i < length; i++) {
				list.add(array[i]);
			}
		}
		return list;
	}

3.測試main函式

public static void main(String []args){
		
		logger.info("測試開始......");
		logger.info("測試List轉換為String[]:");
		List list = new ArrayList();
		list.add("福州");
		list.add("廈門");
		list.add("泉州");
		String[] strArray = convertListToStringArray(list);
		for(int i=0;i<strArray.length;i++){
			logger.info(strArray[i].toString());
		}
		logger.info("測試String[]轉換為List");
		String[] array = new String[]{"福建","廣東","江西"};
		List list2= convertStringArrayToList(array);
		for(int i=0;i<list2.size();i++){
			logger.info(list2.get(i).toString());
		}
		logger.info("測試結束......");
	}

以上,TKS