>  기사  >  Java  >  자바의 HashSet

자바의 HashSet

WBOY
WBOY원래의
2024-08-30 16:20:45802검색

set 인터페이스는 백업용 해시 테이블을 갖고 HashMap의 인스턴스인 HashSet 클래스에 의해 구현됩니다. 하지만 이 클래스는 시간에 따른 요소의 순서를 보장하지 않습니다. 제거, 추가 등과 같은 작업에 대한 시간 성능을 제공하는 이 HashSet 클래스에서는 null 요소가 허용됩니다. 요소가 해시 함수에 의해 버킷 간에 분산된다는 가정하에.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

구문

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

Java HashSet의 생성자

Java HashSet 클래스는 여러 생성자로 구성됩니다. 그들은:

  • HashSet(): 이 생성자 HashSet()을 사용하여 기본 HashSet을 구성할 수 있습니다.
  • HashSet(int 용량): 이 생성자 HashSet(int 용량)을 사용하여 해시세트의 용량을 주어진 정수의 용량으로 초기화할 수 있습니다. 해시세트에 요소를 계속 추가하면 해시세트의 용량이 자동으로 늘어납니다.
  • HashSet(int capacity, float loadFactor): 해시 세트의 용량은 이 생성자 HashSet(를 사용하여 주어진 정수의 용량과 생성자의 매개변수로 지정된 로드 팩터 값으로 초기화될 수 있습니다. int 용량, float loadFactor).
  • HashSet(Collection c): 컬렉션 c의 요소는 이 생성자를 사용하여 해시세트로 초기화됩니다. HashSet(Collection c)

Java HashSet 구현 방법

Java HashSet 클래스는 여러 메소드로 구성됩니다. 그들은:

  • add(E e): 특정 요소가 집합에 없으면 이 Add(E e) 메서드를 사용하여 특정 요소가 집합에 추가됩니다.
  • clear(): 집합의 모든 요소는 Clear() 메서드를 사용하여 제거됩니다.
  • clone(): 해시세트 인스턴스의 얕은 복사본이 Clone() 메서드를 사용하여 반환됩니다. 요소 자체는 복제를 할 수 없습니다.
  • contains(Object o): 지정된 요소가 집합에 있는 경우 Contains(object o) 메서드는 true를 반환합니다.
  • isEmpty(): 집합에 요소가 없으면 isEmpty() 메서드는 true를 반환합니다.
  • iterator(): 설정된 요소에 대한 반복자는 이 메서드 Iterator()를 사용하여 반환됩니다.
  • remove(Object o): 지정된 요소가 집합에 존재하는 경우 이 Remove(object o) 메서드는 지정된 요소를 제거합니다.
  • size(): 집합의 요소 개수는 이 Size() 메서드를 사용하여 반환됩니다.
  • spliterator(): 요소에 대한 늦은 바인딩 및 빠른 분할은 Spliterator() 메서드를 사용하여 집합이 생성되는 것입니다.

Java에서 HashSet을 구현하는 예

아래는 Java에서 HashSet을 구현하는 예입니다.

예시 #1

해시세트를 생성하고 생성된 새 세트에 새 요소를 추가하세요.

코드:

import java.util.HashSet;
import java.util.Set;
//A class Example is created
public class Example {
public static void main(String[] args) {
// A hashset is created
Set<String> months = new HashSet<>();
// New elements are added to the hashset
months.add("January");
months.add("Febraury");
months.add("March");
months.add("April");
months.add("May");
months.add("June");
months.add("July");
months.add("August");
months.add("September");
months.add("October");
months.add("November");
months.add("December");
System.out.println(months);
}
}

출력:

자바의 HashSet

예시 #2

Hashset(컬렉션 c) 생성자의 사용을 보여주는 컬렉션입니다.

코드:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
//A class Example is created
public class Example {
public static void main(String[] args)
{
// A hashset is created
List<Integer> Divby4 = new ArrayList<>();
Divby4.add(4);
Divby4.add(8);
Divby4.add(12);
Divby4.add(16);
Divby4.add(20);
List<Integer> Divby2 = new ArrayList<>();
Divby2.add(2);
Divby2.add(4);
Divby2.add(6);
Divby2.add(8);
Divby2.add(10);
// A hashset is created from another collection Divby4
Set<Integer> Divby4Or2 = new HashSet<>(Divby4);
// Adding the elements of divby2 to the existing hashset
Divby4Or2.addAll(Divby2);
System.out.println(Divby4Or2);
}
}

출력:

자바의 HashSet

예시 #3

해시세트가 비어 있는지 확인하고, 해시세트에 있는 요소 수를 확인하고, 해시세트에 요소가 존재하는지 확인하는 등 해시세트에 대한 작업을 시연하는 Java 프로그램입니다.

코드:

import java.util.HashSet;
import java.util.Set;
//A class Example is created
public class Example {
public static void main(String[] args)
{
// A hashset is created
Set<String> rivers = new HashSet<>();
// performing isempty operation on the set to check if it is empty
System.out.println("Are there no elements in rivers set? : " + rivers.isEmpty());
rivers.add("Kaveri");
rivers.add("Ganga");
rivers.add("Yamuna");
rivers.add("Godavari");
// Checking the size of the hashset
System.out.println("The count of rivers in the hashset are " + rivers.size());
// checking if an element is present in the hashset
String Name = "Ganga";
if(rivers.contains(Name)) {
System.out.println(Name + " is present in the rivers hashset.");
} else {
System.out.println(Name + " is not present in the rivers hashset.");
}
}
}

출력:

자바의 HashSet

예시 #4

해시세트에서 하나의 요소를 제거하고, 다른 컬렉션에 속한 모든 요소를 ​​제거하고, 해시세트에서 특정 조건을 만족하는 요소를 제거하고, 해시세트에서 모든 요소를 ​​제거하는 Java 프로그램입니다.

코드:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
//A class Example is created
public class Example {
public static void main(String[] args)
{
// A hashset is created
Set<Integer> num = new HashSet<>();
num.add(2);
num.add(3);
num.add(4);
num.add(5);
num.add(6);
num.add(7);
num.add(8);
num.add(9);
num.add(10);
System.out.println("Numbers added to the hashset are : " + num);
// An element from the hashset is removed. False is returned if that element doesnt     exists in the hashset
boolean Remove = num.remove(5);
System.out.println("After remove the number 5 from the hashset, the remaining elemnts are => " + num);
// all the elements that belong to a different collection are removed from the hashset
List<Integer> Squares = new ArrayList<>();
Squares.add(4);
Squares.add(9);
num.removeAll(Squares);
System.out.println("After removing all the elements that belong to a different collection => " + num);
// Elements matching a certain condition is removed from the hashset
num.removeIf(num1 -> num1 % 2 == 0);
System.out.println("After removing all the elements matching a certain condition is removed from the hashset => " + num);
// Clearing the hashset
num.clear();
System.out.println("After clearing the hashset => " + num);
}
}

출력:

자바의 HashSet

결론

이 튜토리얼에서는 해시셋의 정의와 해시셋의 개념, 해시셋을 생성하는 구문, 해시셋의 생성자, 해시셋의 메서드, 해시셋 생성을 위한 프로그래밍 예제, 새로 생성된 해시 집합에 요소 추가 등을 이해합니다. 해시세트, 기존 해시세트에서 요소 제거, 해시세트에서 요소 확인

위 내용은 자바의 HashSet의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:자바 해시코드()다음 기사:자바 해시코드()