Java中数组、List、Set互相转换
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
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
staffsSet.add("Mary"); // ok
staffsSet.remove("Tom"); // ok
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);
Object[] result = staffsList.toArray();
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);
Set result = new HashSet(staffsList);
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
Object[] result = staffsSet.toArray();
String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
List<String> result = new ArrayList<>(staffsSet);
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: JNI之------数据类型
- 下一篇: JNI 开发笔记 - 数据类型