码迷,mamicode.com
首页 > 编程语言 > 详细

java中集合,数组,字符串相互转换

时间:2018-06-27 11:28:28      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:for   list   class   str   一个   []   ted   move   new   

数组转List

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

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

    List staffsList = new ArrayList<String>();
    for(String temp: staffs){
      staffsList.add(temp);
    }
    staffsList.add("Mary"); // ok
    staffsList.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"); // ok
staffsSet.remove("Tom"); // ok
  • 1
  • 2
  • 3
  • 4

List转数组

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

Object[] result = staffsList.toArray();
  • 1
  • 2
  • 3
  • 4

List转Set

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

Set result = new HashSet(staffsList);
  • 1
  • 2
  • 3
  • 4

Set转数组

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

Object[] result = staffsSet.toArray();
  • 1
  • 2
  • 3
  • 4

Set转List

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

List<String> result = new ArrayList<>(staffsSet);

java中集合,数组,字符串相互转换

标签:for   list   class   str   一个   []   ted   move   new   

原文地址:https://www.cnblogs.com/nankeyimengningchenlun/p/9232861.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!