Java 数组,集合,list 互相转换

阅读更多
public static void main(String[] args) {
		//list转数组
		List list = new ArrayList();
		list.add("1");
		list.add("2");
		String[] arr = list.toArray(new String[list.size()]);
		for (String each : arr) {
			System.out.println(each);
		}
		
		System.out.println("--- 数组转list - 不变版 ---");
		
		// 数组转list - 不变版
		String[] names = { "Larry", "Moe", "Curly" };
		List nameList = Arrays.asList(names);
		for (String originalName : nameList) {
			System.out.println("originalName: " + originalName);
		}
		//Arrays.asList后的list不能进行add,remove
		//nameList.add("macrotea");
		for (String newName : nameList) {
			System.out.println("newName: " + newName);
		}
		
		System.out.println("--- 数组转list - 可变版 ---");
		
		// 数组转list - 可变版
		String[] books = { "git", "maven", "spring" };
		List bookList = new ArrayList(Arrays.asList(books)); 
		for (String originalBook : bookList) {
			System.out.println("originalBook: " + originalBook);
		}
		//新增book
		bookList.add("hibernate");
		for (String newBook : bookList) {
			System.out.println("newBook: " + newBook);
		}
		
	}
 

你可能感兴趣的:(Java 数组,集合,list 互相转换)