以Java为背景 是一个扩展集合的接口。它是一个无序的对象集合,其中无法存储重复的值。 基本上,set是由 哈希集 , LinkedHashSet 或 有序树 (排序表示法)。 Set有各种添加、删除、清除、大小等方法,以增强此界面的使用。
null
方法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使用集合: Collections类由几个对集合进行操作的方法组成。 (a) 收集addAll() :将所有指定元素添加到指定类型的指定集合。 b) 收藏。不可修改集() :添加元素并返回指定集合的不可修改视图。
// 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 deonstration 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()方法我们将元素添加到集合中
// 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]
本文由 尼基塔·蒂瓦里 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END