요소 존재 확인하기
Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨. 59개 중 25번째.
contains(element) 메서드는 HashSet에 특정 요소가 포함되어 있는지 확인합니다. 요소가 존재하면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
이 메서드는 평균 시간 복잡도가 O(1)이므로 조회에 매우 효율적입니다.
HashSet<String> fruits = new HashSet<>();
fruits.add("Banana");세트에 "Banana"가 있는지 확인합니다
boolean exists1 = fruits.contains("Banana");
// exists1 is true집합에 "Cherry"가 있는지 확인합니다
boolean exists2 = fruits.contains("Cherry");
// exists2 is false챌린지
쉬움checkElement이라는 메서드를 만들고 다음 두 개의 인수를 받도록 하세요:
- 문자열의 HashSet(
set) - 확인할 문자열(
element)
요소가 집합에 있으면 메서드는true를 출력하고, 그렇지 않으면false를 출력해야 합니다.
직접 해보기
import java.util.HashSet;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class Main {
public static void checkElement(HashSet<String> set, String element) {
// 여기에 코드를 작성하세요
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String setString = scanner.nextLine();
String element = scanner.nextLine();
Type setType = new TypeToken<HashSet<String>>(){}.getType();
HashSet<String> set = new Gson().fromJson(setString, setType);
checkElement(set, element);
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리와 흐름의 모든 레슨
직접 연습해 보세요: 온라인 Java 컴파일러