Menu
Coddy logo textTech

Empty와 Size

Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨 — 59개 중 26번째.

isEmpty() 메서드는 HashSet에 요소가 없으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

size() 메서드는 HashSet의 요소 수를 반환합니다.

예를 들어, 먼저 HashSet을 생성해 보겠습니다:

HashSet<String> set = new HashSet<>();

세트가 비어 있는지 확인하려면:

System.out.println(set.isEmpty());
// 출력: true
set.add("Coddy");
System.out.println(set.isEmpty());
// 출력: false

size() 메서드는 세트에 있는 요소의 수를 반환합니다:

System.out.println(set.size());
// Output: 1
challenge icon

챌린지

쉬움

HashSet을 입력으로 받는 이름이 <strong>checkSet</strong>인 메서드를 생성하세요. 이 메서드는 두 줄을 출력해야 합니다:

  • "Empty: <true/false>" 세트가 비어 있는지 여부를 나타냅니다.
  • "Size: <number>" 세트의 요소 수를 나타냅니다.

치트 시트

isEmpty() 메서드는 HashSet에 요소가 없으면 true를 반환하고, 그렇지 않으면 false를 반환합니다:

HashSet<String> set = new HashSet<>();
System.out.println(set.isEmpty()); // true

set.add("Coddy");
System.out.println(set.isEmpty()); // false

size() 메서드는 HashSet의 요소 수를 반환합니다:

System.out.println(set.size()); // 1

직접 해보기

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 checkSet(HashSet<String> set) {
        // 여기에 코드를 작성하세요
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // HashSet을 나타내는 JSON 문자열 읽기 (예: ["Apple","Banana"])
        String setString = scanner.nextLine();
        
        Type setType = new TypeToken<HashSet<String>>(){}.getType();
        HashSet<String> set = new Gson().fromJson(setString, setType);
        
        checkSet(set);
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

논리와 흐름의 모든 레슨