如何在Java中将数组转换为Set?
添加要设置的数组的一种解决方案是使用Collections类的addAll()方法。此方法接受一个collection和一个元素,并将给定的元素添加到指定的Collection中。
示例
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class ArrayToSet {
public static void main(String args[]) {
Integer[] myArray = {23, 93, 56, 92, 39};
Set<Integer> set = new HashSet<Integer>();
Collections.addAll(set, myArray);
System.out.println(set);
}
}输出结果
[23, 39, 56, 92, 93]