【Java提高篇】Java中数组、List和Set的互相转换
1.1、数组转List
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);
(1)需要注意的是, Arrays.asList()
返回一个受指定数组决定的固定大小的列表。所以不能做 add
、 remove
等操作,否则会报错。例如:
List staffsList = Arrays.asList(staffs);
staffsList.add("Mary"); // UnsupportedOperationException
staffsList.remove(0); // UnsupportedOperationException
(2)如果想再做增删操作呢?将数组中的元素一个一个的添加到列表,这样列表的长度就不固定了,可以进行增删操作。
List staffsList = new ArrayList();
for(String temp: staffs){staffsList.add(temp);
}
staffsList.add("Mary"); // ok
staffsList.remove(0); // ok
1.2、数组转Set
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set staffsSet &#61; new HashSet<>(Arrays.asList(staffs));
staffsSet.add("Mary"); // ok
staffsSet.remove("Tom"); // ok
2.1、List转数组
String[] staffs &#61; new String[]{"Tom", "Bob", "Jane"};
List staffsList &#61; Arrays.asList(staffs);
Object[] result &#61; staffsList.toArray();
2.2、List转Set
String[] staffs &#61; new String[]{"Tom", "Bob", "Jane"};
List staffsList &#61; Arrays.asList(staffs);
Set result &#61; new HashSet(staffsList);
3.1、Set转List
String[] staffs &#61; new String[]{"Tom", "Bob", "Jane"};
Set staffsSet &#61; new HashSet<>(Arrays.asList(staffs));
List result &#61; new ArrayList<>(staffsSet);
3.2、Set转数组
String[] staffs &#61; new String[]{"Tom", "Bob", "Jane"};
Set staffsSet &#61; new HashSet<>(Arrays.asList(staffs));
Object[] result &#61; staffsSet.toArray();
转自&#xff1a;https://blog.csdn.net/my_precious/article/details/53010232