Java中array、List、Set互相转换

 

数组转List

String[] staffs = new String[]{"A", "B", "C"};
List staffsList = Arrays.asList(staffs);

//注意: Arrays.asList() 返回一个受指定数组决定的固定大小的列表。所以不能做 add 、 remove 等操作,否则会报错。

List staffsList = Arrays.asList(staffs);
staffsList.add("D"); // UnsupportedOperationException
staffsList.remove(0); // UnsupportedOperationException

//一下方式可以进行增删操作。

List staffsList = new ArrayList();
for(String temp: staffs){
  staffsList.add(temp);
}
staffsList.add("D"); // ok
staffsList.remove(0); // ok

数组转Set

String[] staffs = new String[]{"A", "B", "C"};
Set staffsSet = new HashSet<>(Arrays.asList(staffs));
staffsSet.add("D"); // ok
staffsSet.remove("Tom"); // ok

List转数组

 

String[] staffs = new String[]{"A", "B", "C"};
List staffsList = Arrays.asList(staffs);

Object[] result = staffsList.toArray();

List转Set

String[] staffs = new String[]{"A", "B", "C"};
List staffsList = Arrays.asList(staffs);

Set result = new HashSet(staffsList);

Set转数组

 

String[] staffs = new String[]{"A", "B", "C"};
Set staffsSet = new HashSet<>(Arrays.asList(staffs));

Object[] result = staffsSet.toArray();

Set转List

String[] staffs = new String[]{"A", "B", "C"};
Set staffsSet = new HashSet<>(Arrays.asList(staffs));

List result = new ArrayList<>(staffsSet);

 

版权声明: 本文有 ```...裥簞點 发表于 bloghome博客

转载声明: 可自由转载、引用,但需要属名作者且注明文章出处。

文章链接: https://www.bloghome.com.cn/user/yysblog

你可能感兴趣的:(Java中array、List、Set互相转换)