Инициализация HashSet в Java

Опубликовано: 14 Февраля, 2022

Установить в Java - это интерфейс, расширяющий Collection. Это неупорядоченный набор объектов, в котором нельзя хранить повторяющиеся значения.
В основном набор реализуется с помощью HashSet, LinkedHashSet или TreeSet (отсортированное представление).
В Set есть различные методы для добавления, удаления, удаления, изменения размера и т. Д. Для улучшения использования этого интерфейса.

Method 1: Using Constructor:
In this method first we create an array then convert it to a list and then pass it to the HashSet constructor that accepts another collection.
Integer elements of the set are printed in sorted order.

// 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);
    }
}

Method 2 using Collections:
Collections class consists of several methods that operate on collections.
a) Collection.addAll() : adds all the specified elements to the specified collection of the specified type.
b) Collections.unmodifiableSet() : adds the elements and returns an unmodifiable view of the specified set.

// 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);
    }
}

Method 3: using .add() each time
Create a set and using .add() method we add the elements into the set

// 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]

Автор статьи - Никита Тивари . Если вам нравится GeeksforGeeks, и вы хотели бы внести свой вклад, вы также можете написать статью с помощью provide.geeksforgeeks.org или отправить ее по электронной почте на deposit@geeksforgeeks.org. Посмотрите, как ваша статья появляется на главной странице GeeksforGeeks, и помогите другим гикам.

Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .