SeouliteLab

[Java/자바] HashSet.contains() 메서드 사용 예제 본문

프로그래밍

[Java/자바] HashSet.contains() 메서드 사용 예제

Seoulite Lab 2024. 3. 8. 09:38

HashSet.contains() 메서드 소개

HashSet.contains() 메서드는 HashSet에 특정 요소가 포함되어 있는지 여부를 확인하는 데 사용됩니다. 이 메서드는 boolean 값을 반환하며, HashSet에 해당 요소가 포함되어 있으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

contains() 메서드 사용 예제

아래 예제에서는 HashSet의 contains() 메서드를 사용하여 HashSet에 특정 요소가 포함되어 있는지 여부를 확인하는 방법을 보여줍니다.


import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        HashSet set = new HashSet<>();

        // HashSet에 요소 추가
        set.add("Apple");
        set.add("Banana");
        set.add("Orange");

        // 특정 요소가 HashSet에 포함되어 있는지 확인
        boolean containsApple = set.contains("Apple");
        boolean containsGrape = set.contains("Grape");

        // 결과 출력
        System.out.println("HashSet에 Apple이 포함되어 있나요? " + containsApple);
        System.out.println("HashSet에 Grape이 포함되어 있나요? " + containsGrape);
    }
}

출력:

HashSet에 Apple이 포함되어 있나요? true
HashSet에 Grape이 포함되어 있나요? false