HashSet 사용 방법 (개념, 특징, 메소드 및 예제)

2024. 5. 8. 20:17java

1. HashSet이란?

HashSet은 중복되지 않는 데이터를 순서에 상관없이 저장합니다. 

2. HashSet 생성 방법

HashSet<데이터 타입> 변수명 = new HashSet<데이터 타입>();

 

HashSet<Integer> set1 = new HashSet<Integer>();//HashSet생성
HashSet<Integer> set2 = new HashSet<>();//new에서 타입 파라미터 생략가능
HashSet<Integer> set3 = new HashSet<Integer>(set1);//set1의 모든 값을 가진 HashSet생성 
HashSet<Integer> set4 = new HashSet<Integer>(10);//초기 용량(capacity)지정 
HashSet<Integer> set5 = new HashSet<Integer>(10, 0.7f);//초기 capacity,load factor지정 
HashSet<Integer> set6 = new HashSet<Integer>(Arrays.asList(1,2,3));//초기값 지정

 

3. HashSet 값 추가

Scanner sc = new Scanner(System.in);//scanner를 객체화함		
HashSet<String> hash2 = new HashSet();//HashSet을 생성
hash2.add("hello");//hello라는 값 추가
hash2.add("hi");//hi라는 값 추가

System.out.println(hash2);//hash2의 요소 출력

 

hi와 hello를 추가 해서 요소 2개가 나옵니다.

코드 실행 결과

4. HashSet 값 삭제

Scanner sc = new Scanner(System.in);//Scanner를 객체화		
HashSet<String> hash2 = new HashSet();//HashSet 생성
hash2.add("hello");//hello라는 값 추가
hash2.add("hi");//hi라는 값 추가
hash2.remove("hello");//hello라는 값 추가

System.out.println(hash2);//hash2에 저장된 요소 출력

 

hi와 hello를 추가 했지만, 요소 hello를 없애서 hi가 출력 됩니다.

코드 실행 결과

4. HashSet 값 검색

hashSet의 요소 중에 특정 값이 있는지 없는지 출

Scanner sc = new Scanner(System.in);//Scanner를 객체화		
HashSet<String> hash2 = new HashSet();//HashSet 생성
hash2.add("hello");//hello라는 값 추가

System.out.println(hash2.contains("hello")+" \n"+hash2.contains("hi"));
//hash2에 저장된 요소 중에 hi 및 hello가 있는지 없는지 출력

5.HashSet 메소드  addAll() 사용법

Scanner sc = new Scanner(System.in);//Scanner를 객체화		

HashSet<String> hash2 = new HashSet();//HashSet 생성
HashSet<String> hash1 = new HashSet();//HashSet 생성

hash2.add("hello");//hello라는 값 추가
hash2.add("안녕");//안녕이라는 값 추가
hash2.add("안녕하세요");//안녕하세요라는 값 추가

System.out.println("hash2의 요소:"+hash2);//hash2의 요소 출력

hash1.add("hi");//hi라는 값 추가
hash1.add("hihi");//hihi라는 값 추가
hash1.add("wow");//wow라는 값 추가


hash2.addAll(hash1);//hash2의 요소에 hash1의 모든 요소를 추가

System.out.println("hash2의 요소:"+hash2);//hash2의 요소 출력
System.out.println("hash1의 요소"+hash1);//hash1의 요소 출력

 

hash2의 값을 추가 후, hash1의 값을 추가 후,

addAll() 메서드를 사용 후에 hash1 요소와 hash2 요소가 추가 됩니다.

코드 실행 결과

6.HashSet의 메소드 size()

HashSet의 size() 메소드를 사용해 현재 HashSet의 크기를 구할 수 있습니다

 

Scanner sc = new Scanner(System.in);//Scanner를 객체화		

HashSet<String> hash1 = new HashSet();//HashSet 생성

hash1.add("hello");//hello라는 값 추가
hash1.add("안녕");//안녕이라는 값 추가
hash1.add("안녕하세요");//안녕하세요라는 값 추가

System.out.println("hash1의 요소: "+hash1.size());//hash1의 요소 출력

 

값 3개를 hash1에 추가한 코드입니다.

코드 실행 결과

7. HashSet의 메소드 removeAll() 

removeAll() 메서드는 값을 모두 삭제함

Scanner sc = new Scanner(System.in);//Scanner를 객체화		

HashSet<String> hash2 = new HashSet();//HashSet 생성
HashSet<String> hash1 = new HashSet();//HashSet 생성

hash2.add("hello");//hello라는 값 추가
hash2.add("안녕");//안녕이라는 값 추가
hash2.add("안녕하세요");//안녕하세요라는 값 추가

System.out.println("hash2의 요소: "+hash2);//hash2의 요소 출력

hash1.add("hi");//hi라는 값 추가
hash1.add("hihi");//hihi라는 값 추가
hash1.add("wow");//wow라는 값 추가

hash1.addAll(hash2);//hash1 요소 중에서 hash2 요소 만 제거함

System.out.println("hash2의 값을 추가한 hash1 출력: "+hash1);//hash1의 요소 출력

hash1.removeAll(hash2);//hash1의 요소중에서 hash2의 모든 요소를 제거
System.out.println("hash2 값 제거한 후의 hash1의 값 출력: "+hash1);//hash1의 요소 출력

hash2.removeAll(hash2);//hash2의 값 모두 제거
System.out.println("모든 값 제거한 hash2의 값 출력: "+hash2);//hash2의 요소 출력

 

코드 실행 결과

8. HashSet의 메소드 isEmpty()

isEmpty() 메소드는 hash2의 값이 있으면 false, 없으면 true를 반환합니다.

 

Scanner sc = new Scanner(System.in);//Scanner를 객체화		

HashSet<String> hash2 = new HashSet();//HashSet 생성

System.out.println(hash2.isEmpty()); //hash2 값이 없는지 아닌지 확인
hash2.add("hello");//hello라는 값 추가
hash2.add("안녕");//안녕이라는 값 추가
hash2.add("안녕하세요");//안녕하세요라는 값 추가

System.out.println("hash2의 요소: "+hash2);//hash2의 요소 출력

System.out.println(hash2.isEmpty()); //hash2 값이 없는지 아닌지 확인

9. HashSet의 메소드 clear() 

clear() 메소드는 removeAll() 처럼 저장된 객체들을 전부 삭제함

Scanner sc = new Scanner(System.in);//Scanner를 객체화		

HashSet<String> hash2 = new HashSet();//HashSet 생성

hash2.clear();//hash2 값 모두 삭제함
System.out.println(hash2.isEmpty());//hash2의 값이 없는지 있는지 확인

hash2.add("hello");//hello라는 값 추가
hash2.add("안녕");//안녕이라는 값 추가
hash2.add("안녕하세요");//안녕하세요라는 값 추가

System.out.println(hash2.isEmpty());//hash2의 값이 없는지 있는지 확인

 

 

※ clear() 과 removeAll()의 차이 

 

clear()는 값을 전부 삭제하는 메서드이며,

removeAll()은 지정된 범위에 해당하는 값을 모두 삭제하는 것 입니다.

 

10. 자료 출처

https://dev-coco.tistory.com/36

 

[Java] HashSet

HashSet이란? HashSet은 Set 인터페이스의 구현 클래스이다. 그렇기에 Set의 성질을 그대로 상속 받는다. Set은 객체를 중복해서 저장할 수 없고 하나의 null 값만 저장할 수 있다. 또한 저장 순서가 유지

dev-coco.tistory.com

https://crazykim2.tistory.com/474

 

[JAVA] HashSet이란? & 사용법 정리

안녕하세요 최근 알고리즘을 공부하면서 자바의 다양한 클래스를 알게되고 있는데요 그 동안 개발을 하면서 많이 알고 있다고 생각했는데 끊임없이 나오네요 ㅠ HashSet 클래스에 대해서 설명해

crazykim2.tistory.com

https://hstory0208.tistory.com/entry/Java%EC%9E%90%EB%B0%94-HashSet-%ED%81%B4%EB%9E%98%EC%8A%A4-%EC%82%AC%EC%9A%A9%EB%B2%95

 

[Java/자바] HashSet 클래스 사용법

HashSet HashSet은 Set인터페이스를 구현한 가장 대표적인 컬렉션으로, 중복된 요소를 저장하지 않습니다. 그렇기 때문에 HashSet에 이미 저장되어 있는 요소를 추가하고자 한다면 객체를 저장하기 전

hstory0208.tistory.com

 

'java' 카테고리의 다른 글

substring과 charAt의 차이  (0) 2024.05.07
Arrays 클래스란?  (0) 2024.05.01
StringTokenizer 클래스와 메소드들  (0) 2024.04.30
hasnext()란? - [java]  (0) 2024.04.24
(JAVA) BufferedWriter  (0) 2024.04.24