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

浅浅的花香味﹌ 2022-05-21 02:10 266阅读 0赞

数组转List

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

  • 需要注意的是, Arrays.asList() 返回一个受指定数组决定的固定大小的列表。所以不能做 addremove 等操作,否则会报错。

    1. List staffsList = Arrays.asList(staffs);
    2. staffsList.add("Mary"); // UnsupportedOperationException
    3. staffsList.remove(0); // UnsupportedOperationException
    • 1
    • 2
    • 3
  • 如果想再做增删操作呢?将数组中的元素一个一个添加到列表,这样列表的长度就不固定了,可以进行增删操作。

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

数组转Set

  1. String[] staffs = new String[]{
  2. "Tom", "Bob", "Jane"};
  3. Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
  4. staffsSet.add("Mary"); // ok
  5. staffsSet.remove("Tom"); // ok
  • 1
  • 2
  • 3
  • 4

List转数组

  1. String[] staffs = new String[]{
  2. "Tom", "Bob", "Jane"};
  3. List staffsList = Arrays.asList(staffs);
  4. Object[] result = staffsList.toArray();
  • 1
  • 2
  • 3
  • 4

List转Set

  1. String[] staffs = new String[]{
  2. "Tom", "Bob", "Jane"};
  3. List staffsList = Arrays.asList(staffs);
  4. Set result = new HashSet(staffsList);
  • 1
  • 2
  • 3
  • 4

Set转数组

  1. String[] staffs = new String[]{
  2. "Tom", "Bob", "Jane"};
  3. Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
  4. Object[] result = staffsSet.toArray();
  • 1
  • 2
  • 3
  • 4

Set转List

  1. String[] staffs = new String[]{
  2. "Tom", "Bob", "Jane"};
  3. Set<String> staffsSet = new HashSet<>(Arrays.asList(staffs));
  4. List<String> result = new ArrayList<>(staffsSet);
  • 1
  • 2
  • 3
  • 4

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/my\_precious/article/details/53010232

发表评论

表情:
评论列表 (有 0 条评论,266人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java集合与数组互相转换

    集合与数组互相转换在日常业务开发中必不可少,有时业务需要的是集合,而程序提供的是数组;或者业务需要的是数组,而程序提供的是集合,这就需要转换了。 > 以下简单提供几种常用的