HashSet은 AbstractSet을 확장하고 Set 인터페이스를 구현합니다. 저장을 위해 해시 테이블을 사용하는 컬렉션을 생성합니다.
해시 테이블은 해싱이라는 메커니즘을 사용하여 정보를 저장합니다. 해싱에서 키의 정보 콘텐츠는 해시 코드라고 하는 고유한 값을 결정하는 데 사용됩니다.
그런 다음 해시 코드는 키와 관련된 데이터가 저장되는 인덱스로 사용됩니다. 키를 해시 코드로 변환하는 작업은 자동으로 수행됩니다.
예
Java에서 HashSet을 구현하는 예를 살펴보겠습니다 -
import java.util.*;
public class Demo {
public static void main(String args[]) {
HashSet <String> hashSet = new HashSet <String>();
hashSet.add("One");
hashSet.add("Two");
hashSet.add("Three");
hashSet.add("Four");
hashSet.add("Five");
hashSet.add("Six");
System.out.println("Hash set values = "+ hashSet);
}
} 출력
Hash set values = [Five, Six, One, Four, Two, Three]
예
HashSet에서 요소를 제거하는 또 다른 예를 살펴보겠습니다. -
import java.util.*;
public class Demo {
public static void main(String args[]) {
HashSet <String> newset = new HashSet <String>();
newset.add("Learning");
newset.add("Easy");
newset.add("Simply");
System.out.println("Values before remove: "+newset);
boolean isremoved = newset.remove("Easy");
System.out.println("Return value after remove: "+isremoved);
System.out.println("Values after remove: "+newset);
}
} 출력
Values before remove: [Learning, Easy, Simply] Return value after remove: true Values after remove: [Learning, Simply]