數組轉List 需要註意的是, Arrays.asList() 返回一個受指定數組決定的固定大小的列表。所以不能做 add 、 remove 等操作,否則會報錯。 List staffsList = Arrays.asList(staffs); staffsList.add("Mary"); // ...
數組轉List
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);
-
需要註意的是,
Arrays.asList()
返回一個受指定數組決定的固定大小的列表。所以不能做add
、remove
等操作,否則會報錯。List staffsList = Arrays.asList(staffs); staffsList.add("Mary"); // UnsupportedOperationException staffsList.remove(0); // UnsupportedOperationException
-
如果想再做增刪操作呢?將數組中的元素一個一個添加到列表,這樣列表的長度就不固定了,可以進行增刪操作。
List staffsList = new ArrayList<String>(); for(String temp: staffs){ staffsList.add(temp); } staffsList.add("Mary"); // ok staffsList.remove(0); // ok
數組轉Set
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
staffsSet.add("Mary"); // ok
staffsSet.remove("Tom"); // ok
List轉數組
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);
Object[] result = staffsList.toArray();
List轉Set
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);
Set result = new HashSet(staffsList);
Set轉數組
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
Object[] result = staffsSet.toArray();
Set轉List
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
List<String> result = new ArrayList<>(staffsSet);