欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-05 14:31:08
数组转List 需要注意的是, Arrays.asList() 返回一个受指定数组决定的固定大小的列表。所以不能做 add 、 remove 等操作,否则会报错。 List staffsList = Arrays.asList(staffs); staffsList.add("Mary"); // ......

数组转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);