数组转换集合or集合转换成数组

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z_5201314/article/details/89463008

1.数组转换为集合

  • 使用数组的工具类Arrays的方法asList
  • 需要注意,只能转换为List集
public class ArrayToListDemo {
	public static void main(String[] args) {
		String[] array = {"one","two","three","four","five"};
		
		List<String> list = Arrays.asList(array);
		System.out.println(list.size());
		System.out.println(list);
		
		list.set(1, "2");
		System.out.println(list);
		/*
		 * 对集合元素的操作就是对原数组对应元素的操作
		 */
		for(String str : array){
			System.out.println(str);
		}
		/*
		 * 从数组转换过来的集合是不能添加新元素的
		 * 否则会抛出不受支持的操作异常
		 * 因为对集合元素操作就是对原数组操作,添加
		 * 元素会导致数组扩容,从而表示不了原数组。
		 */
//		list.add("six");
		
		/*
		 * 想添加新元素,需要自行创建一个集合
		 */
		List<String> list1 
			= new ArrayList<String>(list);
	
		System.out.println("list1:"+list1);
		list1.add("six");
		System.out.println("list1:"+list1);
		
	}
}

输出结果:
在这里插入图片描述

2.集合转换成数组

  • Collection提供了方法 toArray
  • 可以将当前集合转换为一个数组
public class CollectionToArrayDemo {
	public static void main(String[] args) {
		Collection<String> c = new ArrayList<String>();
		c.add("one");
		c.add("two");
		c.add("three");
		c.add("four");
		c.add("five");
		System.out.println(c);
		//不常用
//		Object[] array = c.toArray();
		
		String[] array = c.toArray(new String[c.size()]);
		System.out.println(array.length);
		for(String str : array){
			System.out.println(str);
		}
	}
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/z_5201314/article/details/89463008