• Java: 数组、列表和集合的互相转换


    1. Array 转 List

    String[] city = {"Nanjing","Shanghai","Beijing"};
    List<String> cityList = Arrays.asList(city);
    

     注意:数组转换得到的List大小固定,不能执行add、remove操作,否则会抛出以下异常:

    cityList.add("Xiamen");
    cityList.remove(2);

     如果想控制List大小,只能将Array中的元素依此加入到List当中。。。


    2. List 转 Array

    Object[] cityArray = cityList.toArray();
    
    for(Object x:cityArray)
         System.out.println(x);
    

     注意:因为 List 转换成 Array时,无法获知List内存储的是什么类型数据,所以采用Object类创建数组。运行结果如下:


    3. List 转 Set

     String[] city = {"Nanjing","Shanghai","Beijing"};
     List<String> cityList = Arrays.asList(city);
    
     Set listToSet = new HashSet(cityList);
    

      


    4. Set 转 List

    List list = new ArrayList(set);
    

      


    5. Array 转 Set

    注意:先把Array转换成List,再转换为Set

    String[] city = {"Nanjing","Shanghai","Beijing"};
    Set set = new HashSet(Arrays.asList(city));
    

      


    6. Set 转 Array

    String[] city = {"Nanjing","Shanghai","Beijing"};
    Set set = new HashSet(Arrays.asList(city));
    Object[] setToArray = set.toArray();
    

      

  • 相关阅读:
    异或和之和
    Wannafly挑战赛19C:多彩的树
    HDU 6035 树形dp
    利用C++套接字发送邮件
    洛谷P3368树状模板(区间更新+单点查询+差分)
    CCF 201903-1 小中大
    关于树状数组
    CODEVS 4189 (前缀是否出现)
    关于字典树
    hdu 1022 Train Problem
  • 原文地址:https://www.cnblogs.com/huiAlex/p/8242161.html
Copyright © 2020-2023  润新知