Java中数组、List、Set互相转换

2018-03-27 11:36:58

数组转List

String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);12
  • 需要注意的是, Arrays.asList() 返回一个受指定数组决定的固定大小的列表。所以不能做 add 、 remove等操作,否则会报错。

    List staffsList = Arrays.asList(staffs);
    staffsList.add("Mary"); // UnsupportedOperationExceptionstaffsList.remove(0); // UnsupportedOperationException
    • 1

    • 2

    • 3

  • 如果想再做增删操作呢?将数组中的元素一个一个添加到列表,这样列表的长度就不固定了,可以进行增删操作。

    List staffsList = new ArrayList<String>();for(String temp: staffs){
      staffsList.add(temp);
    }
    staffsList.add("Mary"); // okstaffsList.remove(0); // ok
    • 1

    • 2

    • 3

    • 4

    • 5

    • 6


数组转Set

String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
staffsSet.add("Mary"); // okstaffsSet.remove("Tom"); // ok1234

List转数组

String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);

Object[] result = staffsList.toArray();1234

List转Set

String[] staffs = new String[]{"Tom", "Bob", "Jane"};
List staffsList = Arrays.asList(staffs);

Set result = new HashSet(staffsList);1234

Set转数组

String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));

Object[] result = staffsSet.toArray();1234

Set转List

String[] staffs = new String[]{"Tom", "Bob", "Jane"};
Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));

List<String> result = new ArrayList<>(staffsSet);
  • 2020-12-07 22:06:13

    System Extension Blocked - warning

    After upgrading your macOS computer to High Sierra 10.13.4 or higher (starting in April 2018), you may see a message about a System Extension Blocked. At Williams we have seen this warning appear for these programs:

  • 2020-12-08 08:57:12

    win10上使用win-sshfs

    首先在GitHub上下载DokanSetup-1.0.5.1000和WinSSHFS-1.6.1.13-devel 注意:Dokan不能使用最新的版本,得使用1.0.5版本。要不win-sshfs会报Dokan版本错误的问题。(win10版本)

  • 2020-12-08 11:51:54

    Ubuntu安装Node.js和npm

    Node.js是基于Chrome的JavaScript构建的跨平台JavaScript运行时环境,npm是Node.js的默认程序包管理器,也是世界上最大的软件注册表。本篇文章展示了三种在Ubuntu 20.04服务器上安装Node.js和npm的方法。

  • 2020-12-08 17:13:57

    nvm卸载、安装node和npm

    1、node.js、nvm、 npm (1)在cmd中输入`where node`找到node长须所在位置进行删除 (2)确保计算机-环境变量删除相关引用 (3)在cmd中输入`node -v` ,得到以下结果,删除成功

  • 2020-12-08 17:23:36

    Window下完全卸载删除Nodejs

    1.从卸载程序卸载程序和功能。 2.重新启动(或者您可能会从任务管理器中杀死所有与节点相关的进程)。 3.寻找这些文件夹并删除它们(及其内容)(如果还有)。根据您安装的版本,UAC设置和CPU架构,这些可能或可能不存在:

  • 2020-12-09 08:48:45

    nodejs版本以及其对应的npm版本

    正在寻找某个大版本的最新版? Node.js 10.x Node.js 8.x Node.js 6.x Node.js 4.x Node.js 0.12.x Node.js 0.10.x 所有版本