Java 初始化HashSet
Java中的Set是一个扩展Collection的接口。它是一个无序的对象集合,其中不能存储重复的值。
基本上,set是由HashSet、LinkedHashSet或TreeSet(排序表示)实现的。
Set有各种方法来添加、删除清除、大小等,以提高该接口的使用。
方法1:使用构造函数:
在这个方法中,我们首先创建一个数组,然后将其转换为一个列表,再将其传递给接受另一个集合的HashSet构造函数。
集合的整数元素按排序顺序打印。
// Java code for initializing a Set
import java.util.*;
public class Set_example {
public static void main(String[] args)
{
// creating and initializing an array (of non
// primitive type)
Integer arr[] = { 5, 6, 7, 8, 1, 2, 3, 4, 3 };
// Set demonstration using HashSet Constructor
Set<Integer> set = new HashSet<>(Arrays.asList(arr));
// Duplicate elements are not printed in a set.
System.out.println(set);
}
}
使用集合的方法2:
集合类包括几个对集合进行操作的方法。
a) Collection.addAll() : 将所有指定的元素添加到指定类型的集合中。
b) Collections.unmodifiableSet() : 添加元素并返回一个指定集合的不可修改的视图。
// Java code for initializing a Set
import java.util.*;
public class Set_example {
public static void main(String[] args)
{
// creating and initializing an array (of non
// primitive type)
Integer arr[] = { 5, 6, 7, 8, 1, 2, 3, 4, 3 };
// Set demonstration using Collections.addAll
Set<Integer> set = Collections.<Integer> emptySet();
Collections.addAll(set =
new HashSet<Integer>(Arrays.asList(arr)));
// initializing set using Collections.unmodifiable set
Set<Integer> set2 =
Collections.unmodifiableSet(new HashSet<Integer>
(Arrays.asList(arr)));
// Duplicate elements are not printed in a set.
System.out.println(set);
}
}
方法3:每次使用.add()
创建一个集合,使用.add()方法,我们将元素添加到集合中
// Java code for initializing a Set
import java.util.*;
public class Set_example {
public static void main(String[] args)
{
// Create a set
Set<Integer> set = new HashSet<Integer>();
// Add some elements to the set
set.add(1);
set.add(2);
set.add(3);
set.add(4);
set.add(5);
set.add(6);
set.add(7);
set.add(8);
// Adding a duplicate element has no effect
set.add(3);
System.out.println(set);
}
}
输出:
[1, 2, 3, 4, 5, 6, 7, 8]
极客教程