Java: 数组、列表和集合的互相转换
1. Array 转 List
String[] city = {"Nanjing","Shanghai","Beijing"}; List<String> cityList = Arrays.asList(city);
注意:数组转换得到的List大小固定,不能执行add、remove操作,否则会抛出以下异常:
cityList.add("Xiamen"); cityList.remove(2);
如果想控制List大小,只能将Array中的元素依此加入到List当中。。。
2. List 转 Array
Object[] cityArray = cityList.toArray(); for(Object x:cityArray) System.out.println(x);
注意:因为 List 转换成 Array时,无法获知List内存储的是什么类型数据,所以采用Object类创建数组。运行结果如下:
3. List 转 Set
String[] city = {"Nanjing","Shanghai","Beijing"}; List<String> cityList = Arrays.asList(city); Set listToSet = new HashSet(cityList);
4. Set 转 List
List list = new ArrayList(set);
5. Array 转 Set
注意:先把Array转换成List,再转换为Set
String[] city = {"Nanjing","Shanghai","Beijing"}; Set set = new HashSet(Arrays.asList(city));
6. Set 转 Array
String[] city = {"Nanjing","Shanghai","Beijing"}; Set set = new HashSet(Arrays.asList(city)); Object[] setToArray = set.toArray();