zoukankan      html  css  js  c++  java
  • Java中数组、List、Set互相转换

    数组转List

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

      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);
  • 相关阅读:
    Git 常用命令 Better
    HTTP Cookie 总结 Better
    clientWidth, offsetWidth, scrollWidth的区别 Better
    Math.round() 0.5时的特殊性 Better
    screenY、pageY、clientY、offsetY的区别 Better
    Oracle 数据快速导出工具:sqluldr2
    使用 barman的备份和归档PostgreSQL
    Android RK 内置应用 不可卸载
    AS SerialPort 编译依赖库
    RK 看门狗 WatchDog
  • 原文地址:https://www.cnblogs.com/snake23/p/9630110.html
Copyright © 2011-2022 走看看