HashSet<T> 생성자

정의

HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

오버로드

HashSet<T>()

비어 있으며 집합 형식에 대한 기본 같음 비교자를 사용하는 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

HashSet<T>(IEnumerable<T>)

집합 형식에 대한 기본 같음 비교자를 사용하고 지정된 컬렉션에서 복사한 요소가 들어 있으며 복사된 요소 수를 수용하기에 용량이 충분한 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

HashSet<T>(IEqualityComparer<T>)

비어 있으며 집합 형식에 대한 지정된 같음 비교자를 사용하는 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

HashSet<T>(Int32)

비어 있지만 capacity 항목에 대한 공간이 예약되어 있고 집합 형식에 대한 기본 같음 비교자를 사용하는 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

HashSet<T>(IEnumerable<T>, IEqualityComparer<T>)

집합 형식에 대한 지정된 같음 비교자를 사용하고 지정된 컬렉션에서 복사한 요소가 들어 있으며 복사된 요소 수를 수용하기에 용량이 충분한 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

HashSet<T>(Int32, IEqualityComparer<T>)

집합 형식에 대해 지정된 같음 비교자를 사용하고 capacity 요소를 수용할 수 있을 만큼 용량이 충분한 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

HashSet<T>(SerializationInfo, StreamingContext)
사용되지 않음.

serialize된 데이터를 사용하여 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

HashSet<T>()

Source:
HashSet.cs
Source:
HashSet.cs
Source:
HashSet.cs

비어 있으며 집합 형식에 대한 기본 같음 비교자를 사용하는 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

public:
 HashSet();
public HashSet ();
Public Sub New ()

예제

다음 예제에서는 두 HashSet<T> 개체를 만들고 채우는 방법을 보여 줍니다. 이 예제는 메서드에 제공된 더 큰 예제의 UnionWith 일부입니다.

HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();

for (int i = 0; i < 5; i++)
{
    // Populate numbers with just even numbers.
    evenNumbers.Add(i * 2);

    // Populate oddNumbers with just odd numbers.
    oddNumbers.Add((i * 2) + 1);
}
Dim evenNumbers As HashSet(Of Integer) = New HashSet(Of Integer)()
Dim oddNumbers As HashSet(Of Integer) = New HashSet(Of Integer)()

For i As Integer = 0 To 4

    ' Populate evenNumbers with only even numbers.
    evenNumbers.Add(i * 2)

    ' Populate oddNumbers with only odd numbers.
    oddNumbers.Add((i * 2) + 1)
Next i

설명

개체의 HashSet<T> 용량은 개체가 보유할 수 있는 요소의 수입니다. HashSet<T> 개체에 요소가 추가되면 개체의 용량이 자동으로 증가합니다.

이 생성자는 O(1) 작업입니다.

적용 대상

HashSet<T>(IEnumerable<T>)

Source:
HashSet.cs
Source:
HashSet.cs
Source:
HashSet.cs

집합 형식에 대한 기본 같음 비교자를 사용하고 지정된 컬렉션에서 복사한 요소가 들어 있으며 복사된 요소 수를 수용하기에 용량이 충분한 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

public:
 HashSet(System::Collections::Generic::IEnumerable<T> ^ collection);
public HashSet (System.Collections.Generic.IEnumerable<T> collection);
new System.Collections.Generic.HashSet<'T> : seq<'T> -> System.Collections.Generic.HashSet<'T>
Public Sub New (collection As IEnumerable(Of T))

매개 변수

collection
IEnumerable<T>

해당 요소가 새 집합에 복사되는 컬렉션입니다.

예외

collection이(가) null인 경우

예제

다음 예제에서는 기존 집합에서 컬렉션을 만드는 HashSet<T> 방법을 보여줍니다. 이 예제에서는 각각 짝수 및 홀수 정수로 두 집합을 만듭니다. 그런 다음 짝수 정수 집합에서 세 번째 HashSet<T> 개체를 만듭니다.

HashSet<int> evenNumbers = new HashSet<int>();
HashSet<int> oddNumbers = new HashSet<int>();

for (int i = 0; i < 5; i++)
{
    // Populate numbers with just even numbers.
    evenNumbers.Add(i * 2);

    // Populate oddNumbers with just odd numbers.
    oddNumbers.Add((i * 2) + 1);
}

Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count);
DisplaySet(evenNumbers);

Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count);
DisplaySet(oddNumbers);

// Create a new HashSet populated with even numbers.
HashSet<int> numbers = new HashSet<int>(evenNumbers);
Console.WriteLine("numbers UnionWith oddNumbers...");
numbers.UnionWith(oddNumbers);

Console.Write("numbers contains {0} elements: ", numbers.Count);
DisplaySet(numbers);

void DisplaySet(HashSet<int> collection)
{
    Console.Write("{");
    foreach (int i in collection)
    {
        Console.Write(" {0}", i);
    }
    Console.WriteLine(" }");
}

/* This example produces output similar to the following:
* evenNumbers contains 5 elements: { 0 2 4 6 8 }
* oddNumbers contains 5 elements: { 1 3 5 7 9 }
* numbers UnionWith oddNumbers...
* numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 }
*/
Shared Sub Main()

    Dim evenNumbers As HashSet(Of Integer) = New HashSet(Of Integer)()
    Dim oddNumbers As HashSet(Of Integer) = New HashSet(Of Integer)()

    For i As Integer = 0 To 4

        ' Populate evenNumbers with only even numbers.
        evenNumbers.Add(i * 2)

        ' Populate oddNumbers with only odd numbers.
        oddNumbers.Add((i * 2) + 1)
    Next i

    Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count)
    DisplaySet(evenNumbers)

    Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count)
    DisplaySet(oddNumbers)

    ' Create a new HashSet populated with even numbers.
    Dim numbers As HashSet(Of Integer) = New HashSet(Of Integer)(evenNumbers)
    Console.WriteLine("numbers UnionWith oddNumbers...")
    numbers.UnionWith(oddNumbers)

    Console.Write("numbers contains {0} elements: ", numbers.Count)
    DisplaySet(numbers)
End Sub

설명

개체의 HashSet<T> 용량은 개체가 보유할 수 있는 요소의 수입니다. HashSet<T> 개체에 요소가 추가되면 개체의 용량이 자동으로 증가합니다.

중복 항목이 포함된 경우 collection 집합에는 각 고유 요소 중 하나가 포함됩니다. 예외는 throw되지 않습니다. 따라서 결과 집합의 크기는 의 collection크기와 동일하지 않습니다.

이 생성자는 O(n) 작업입니다. 여기서 n 는 매개 변수의 요소 collection 수입니다.

적용 대상

HashSet<T>(IEqualityComparer<T>)

Source:
HashSet.cs
Source:
HashSet.cs
Source:
HashSet.cs

비어 있으며 집합 형식에 대한 지정된 같음 비교자를 사용하는 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

public:
 HashSet(System::Collections::Generic::IEqualityComparer<T> ^ comparer);
public HashSet (System.Collections.Generic.IEqualityComparer<T> comparer);
public HashSet (System.Collections.Generic.IEqualityComparer<T>? comparer);
new System.Collections.Generic.HashSet<'T> : System.Collections.Generic.IEqualityComparer<'T> -> System.Collections.Generic.HashSet<'T>
Public Sub New (comparer As IEqualityComparer(Of T))

매개 변수

comparer
IEqualityComparer<T>

집합의 값을 비교하려면 IEqualityComparer<T> 구현을 사용하고, 집합 형식에 대한 기본 EqualityComparer<T> 구현을 사용하려면 null을(를) 지정합니다.

설명

개체의 HashSet<T> 용량은 개체가 보유할 수 있는 요소의 수입니다. HashSet<T> 개체에 요소가 추가되면 개체의 용량이 자동으로 증가합니다.

이 생성자는 O(1) 작업입니다.

적용 대상

HashSet<T>(Int32)

Source:
HashSet.cs
Source:
HashSet.cs
Source:
HashSet.cs

비어 있지만 capacity 항목에 대한 공간이 예약되어 있고 집합 형식에 대한 기본 같음 비교자를 사용하는 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

public:
 HashSet(int capacity);
public HashSet (int capacity);
new System.Collections.Generic.HashSet<'T> : int -> System.Collections.Generic.HashSet<'T>
Public Sub New (capacity As Integer)

매개 변수

capacity
Int32

의 초기 크기입니다 HashSet<T>.

설명

크기 조정은 상대적으로 비용이 많이 들기 때문에(다시 해시 필요) 의 값 capacity에 따라 초기 용량을 설정하여 크기를 조정해야 하는 필요성을 최소화하려고 합니다.

적용 대상

HashSet<T>(IEnumerable<T>, IEqualityComparer<T>)

Source:
HashSet.cs
Source:
HashSet.cs
Source:
HashSet.cs

집합 형식에 대한 지정된 같음 비교자를 사용하고 지정된 컬렉션에서 복사한 요소가 들어 있으며 복사된 요소 수를 수용하기에 용량이 충분한 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

public:
 HashSet(System::Collections::Generic::IEnumerable<T> ^ collection, System::Collections::Generic::IEqualityComparer<T> ^ comparer);
public HashSet (System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IEqualityComparer<T> comparer);
public HashSet (System.Collections.Generic.IEnumerable<T> collection, System.Collections.Generic.IEqualityComparer<T>? comparer);
new System.Collections.Generic.HashSet<'T> : seq<'T> * System.Collections.Generic.IEqualityComparer<'T> -> System.Collections.Generic.HashSet<'T>
Public Sub New (collection As IEnumerable(Of T), comparer As IEqualityComparer(Of T))

매개 변수

collection
IEnumerable<T>

해당 요소가 새 집합에 복사되는 컬렉션입니다.

comparer
IEqualityComparer<T>

집합의 값을 비교하려면 IEqualityComparer<T> 구현을 사용하고, 집합 형식에 대한 기본 EqualityComparer<T> 구현을 사용하려면 null을(를) 지정합니다.

예외

collectionnull입니다.

예제

다음 예제에서는 제공된 IEqualityComparer<T> 를 사용하여 차량 유형 컬렉션의 요소에 대한 대/소문자를 구분하지 않는 비교를 HashSet<T> 허용합니다.

#using <System.Core.dll>

using namespace System;
using namespace System::Collections::Generic;

ref class Program
{
public:
    static void Main()
    {
        HashSet<String^> ^allVehicles = gcnew HashSet<String^>(StringComparer::OrdinalIgnoreCase);
        List<String^>^ someVehicles = gcnew List<String^>();

        someVehicles->Add("Planes");
        someVehicles->Add("Trains");
        someVehicles->Add("Automobiles");

        // Add in the vehicles contained in the someVehicles list.
        allVehicles->UnionWith(someVehicles);

        Console::WriteLine("The current HashSet contains:\n");
        for each (String^ vehicle in allVehicles)
        {
            Console::WriteLine(vehicle);
        }

        allVehicles->Add("Ships");
        allVehicles->Add("Motorcycles");
        allVehicles->Add("Rockets");
        allVehicles->Add("Helicopters");
        allVehicles->Add("Submarines");

        Console::WriteLine("\nThe updated HashSet contains:\n");
        for each (String^ vehicle in allVehicles)
        {
            Console::WriteLine(vehicle);
        }

        // Verify that the 'All Vehicles' set contains at least the vehicles in
        // the 'Some Vehicles' list.
        if (allVehicles->IsSupersetOf(someVehicles))
        {
            Console::Write("\nThe 'All' vehicles set contains everything in ");
            Console::WriteLine("'Some' vechicles list.");
        }

        // Check for Rockets. Here the OrdinalIgnoreCase comparer will compare
        // true for the mixed-case vehicle type.
        if (allVehicles->Contains("roCKeTs"))
        {
            Console::WriteLine("\nThe 'All' vehicles set contains 'roCKeTs'");
        }

        allVehicles->ExceptWith(someVehicles);
        Console::WriteLine("\nThe excepted HashSet contains:\n");
        for each (String^ vehicle in allVehicles)
        {
            Console::WriteLine(vehicle);
        }

        // Remove all the vehicles that are not 'super cool'.
        allVehicles->RemoveWhere(gcnew Predicate<String^>(&isNotSuperCool));

        Console::WriteLine("\nThe super cool vehicles are:\n");
        for each (String^ vehicle in allVehicles)
        {
            Console::WriteLine(vehicle);
        }
    }

private:
    // Predicate to determine vehicle 'coolness'.
    static bool isNotSuperCool(String^ vehicle)
    {
        bool superCool = (vehicle == "Helicopters") || (vehicle == "Motorcycles");

        return !superCool;
    }
};

int main()
{
    Program::Main();
}

// The program writes the following output to the console::
//
// The current HashSet contains:
//
// Planes
// Trains
// Automobiles
//
// The updated HashSet contains:
//
// Planes
// Trains
// Automobiles
// Ships
// Motorcycles
// Rockets
// Helicopters
// Submarines
//
// The 'All' vehicles set contains everything in 'Some' vechicles list.
//
// The 'All' vehicles set contains 'roCKeTs'
//
// The excepted HashSet contains:
//
// Ships
// Motorcycles
// Rockets
// Helicopters
// Submarines
//
// The super cool vehicles are:
//
// Motorcycles
// Helicopters
HashSet<string> allVehicles = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
List<string> someVehicles = new List<string>();

someVehicles.Add("Planes");
someVehicles.Add("Trains");
someVehicles.Add("Automobiles");

// Add in the vehicles contained in the someVehicles list.
allVehicles.UnionWith(someVehicles);

Console.WriteLine("The current HashSet contains:\n");
foreach (string vehicle in allVehicles)
{
    Console.WriteLine(vehicle);
}

allVehicles.Add("Ships");
allVehicles.Add("Motorcycles");
allVehicles.Add("Rockets");
allVehicles.Add("Helicopters");
allVehicles.Add("Submarines");

Console.WriteLine("\nThe updated HashSet contains:\n");
foreach (string vehicle in allVehicles)
{
    Console.WriteLine(vehicle);
}

// Verify that the 'All Vehicles' set contains at least the vehicles in
// the 'Some Vehicles' list.
if (allVehicles.IsSupersetOf(someVehicles))
{
    Console.Write("\nThe 'All' vehicles set contains everything in ");
    Console.WriteLine("'Some' vechicles list.");
}

// Check for Rockets. Here the OrdinalIgnoreCase comparer will compare
// true for the mixed-case vehicle type.
if (allVehicles.Contains("roCKeTs"))
{
    Console.WriteLine("\nThe 'All' vehicles set contains 'roCKeTs'");
}

allVehicles.ExceptWith(someVehicles);
Console.WriteLine("\nThe excepted HashSet contains:\n");
foreach (string vehicle in allVehicles)
{
    Console.WriteLine(vehicle);
}

// Remove all the vehicles that are not 'super cool'.
allVehicles.RemoveWhere(isNotSuperCool);

Console.WriteLine("\nThe super cool vehicles are:\n");
foreach (string vehicle in allVehicles)
{
    Console.WriteLine(vehicle);
}

// Predicate to determine vehicle 'coolness'.
bool isNotSuperCool(string vehicle)
{
    bool superCool = (vehicle == "Helicopters") || (vehicle == "Motorcycles");

    return !superCool;
}

// The program writes the following output to the console.
//
// The current HashSet contains:
//
// Planes
// Trains
// Automobiles
//
// The updated HashSet contains:
//
// Planes
// Trains
// Automobiles
// Ships
// Motorcycles
// Rockets
// Helicopters
// Submarines
//
// The 'All' vehicles set contains everything in 'Some' vechicles list.
//
// The 'All' vehicles set contains 'roCKeTs'
//
// The excepted HashSet contains:
//
// Ships
// Motorcycles
// Rockets
// Helicopters
// Submarines
//
// The super cool vehicles are:
//
// Motorcycles
// Helicopters
Imports System.Collections.Generic

Class Program
    Public Shared Sub Main()
        Dim allVehicles As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase)
        Dim someVehicles As New List(Of String)()

        someVehicles.Add("Planes")
        someVehicles.Add("Trains")
        someVehicles.Add("Automobiles")

        ' Add in the vehicles contained in the someVehicles list.
        allVehicles.UnionWith(someVehicles)

        Console.WriteLine("The current HashSet contains:" + Environment.NewLine)
        For Each vehicle As String In allVehicles
            Console.WriteLine(vehicle)
        Next vehicle

        allVehicles.Add("Ships")
        allVehicles.Add("Motorcycles")
        allVehicles.Add("Rockets")
        allVehicles.Add("Helicopters")
        allVehicles.Add("Submarines")

        Console.WriteLine(Environment.NewLine + "The updated HashSet contains:" + Environment.NewLine)
        For Each vehicle As String In allVehicles
            Console.WriteLine(vehicle)
        Next vehicle

        ' Verify that the 'All Vehicles' set contains at least the vehicles in
        ' the 'Some Vehicles' list.
        If allVehicles.IsSupersetOf(someVehicles) Then
            Console.Write(Environment.NewLine + "The 'All' vehicles set contains everything in ")
            Console.WriteLine("'Some' vechicles list.")
        End If

        ' Check for Rockets. Here the OrdinalIgnoreCase comparer will compare
        ' True for the mixed-case vehicle type.
        If allVehicles.Contains("roCKeTs") Then
            Console.WriteLine(Environment.NewLine + "The 'All' vehicles set contains 'roCKeTs'")
        End If

        allVehicles.ExceptWith(someVehicles)
        Console.WriteLine(Environment.NewLine + "The excepted HashSet contains:" + Environment.NewLine)
        For Each vehicle As String In allVehicles
            Console.WriteLine(vehicle)
        Next vehicle

        ' Remove all the vehicles that are not 'super cool'.
        allVehicles.RemoveWhere(AddressOf isNotSuperCool)

        Console.WriteLine(Environment.NewLine + "The super cool vehicles are:" + Environment.NewLine)
        For Each vehicle As String In allVehicles
            Console.WriteLine(vehicle)
        Next vehicle
    End Sub

    ' Predicate to determine vehicle 'coolness'.
    Private Shared Function isNotSuperCool(vehicle As String) As Boolean
        Dim notSuperCool As Boolean = _
            (vehicle <> "Helicopters") And (vehicle <> "Motorcycles")

        Return notSuperCool
    End Function
End Class

'
' The program writes the following output to the console.
'
' The current HashSet contains:
'
' Planes
' Trains
' Automobiles
'
' The updated HashSet contains:
'
' Planes
' Trains
' Automobiles
' Ships
' Motorcycles
' Rockets
' Helicopters
' Submarines
'
' The 'All' vehicles set contains everything in 'Some' vechicles list.
'
' The 'All' vehicles set contains 'roCKeTs'
'
' The excepted HashSet contains:
'
' Ships
' Motorcycles
' Rockets
' Helicopters
' Submarines
'
' The super cool vehicles are:
'
' Motorcycles
' Helicopters

설명

개체의 HashSet<T> 용량은 개체가 보유할 수 있는 요소의 수입니다. HashSet<T> 개체에 요소가 추가되면 개체의 용량이 자동으로 증가합니다.

중복 항목이 포함된 경우 collection 집합에는 각 고유 요소 중 하나가 포함됩니다. 예외는 throw되지 않습니다. 따라서 결과 집합의 크기는 의 collection크기와 동일하지 않습니다.

이 생성자는 O(n) 작업입니다. 여기서 n 는 매개 변수의 요소 collection 수입니다.

적용 대상

HashSet<T>(Int32, IEqualityComparer<T>)

Source:
HashSet.cs
Source:
HashSet.cs
Source:
HashSet.cs

집합 형식에 대해 지정된 같음 비교자를 사용하고 capacity 요소를 수용할 수 있을 만큼 용량이 충분한 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

public:
 HashSet(int capacity, System::Collections::Generic::IEqualityComparer<T> ^ comparer);
public HashSet (int capacity, System.Collections.Generic.IEqualityComparer<T>? comparer);
public HashSet (int capacity, System.Collections.Generic.IEqualityComparer<T> comparer);
new System.Collections.Generic.HashSet<'T> : int * System.Collections.Generic.IEqualityComparer<'T> -> System.Collections.Generic.HashSet<'T>
Public Sub New (capacity As Integer, comparer As IEqualityComparer(Of T))

매개 변수

capacity
Int32

의 초기 크기입니다 HashSet<T>.

comparer
IEqualityComparer<T>

집합의 값을 비교하려면 IEqualityComparer<T> 구현을 사용하고, 집합 형식에 대한 기본 IEqualityComparer<T> 구현을 사용하려면 null(Visual Basic의 경우 Nothing)을 지정합니다.

설명

크기 조정은 상대적으로 비용이 많이 들기 때문에(다시 해시 필요) 의 값 capacity에 따라 초기 용량을 설정하여 크기를 조정해야 하는 필요성을 최소화하려고 합니다.

적용 대상

HashSet<T>(SerializationInfo, StreamingContext)

Source:
HashSet.cs
Source:
HashSet.cs
Source:
HashSet.cs

주의

This API supports obsolete formatter-based serialization. It should not be called or extended by application code.

serialize된 데이터를 사용하여 HashSet<T> 클래스의 새 인스턴스를 초기화합니다.

protected:
 HashSet(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected HashSet (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
[System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
protected HashSet (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
new System.Collections.Generic.HashSet<'T> : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Collections.Generic.HashSet<'T>
[<System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
new System.Collections.Generic.HashSet<'T> : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Collections.Generic.HashSet<'T>
Protected Sub New (info As SerializationInfo, context As StreamingContext)

매개 변수

info
SerializationInfo

HashSet<T> 개체를 serialize하는 데 필요한 정보가 포함된 SerializationInfo 개체입니다.

context
StreamingContext

HashSet<T> 개체에 연결되어 있는 serialize된 스트림의 소스와 대상이 포함된 StreamingContext 구조체입니다.

특성

설명

이 생성자는 역직렬화 중에 호출되어 스트림을 통해 전송되는 개체를 재구성합니다. 자세한 내용은 XML 및 SOAP Serialization합니다.

적용 대상