Menu
Coddy logo textTech

要素の削除

CoddyのJavaジャーニー「ロジックとフロー」セクションの一部 — レッスン 24/59。

remove(element) メソッドは、指定された要素が HashSet に存在する場合にその要素を HashSet から削除します。

HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");

セットから "Apple" を削除する

fruits.remove("Apple");

上記のコードを実行した後、セット fruits には:

[]
challenge icon

チャレンジ

簡単

名前が <strong>removeElement</strong> のメソッドを作成してください。このメソッドは 2 つの引数を受け取ります:

  1. 文字列の HashSet (set)
  2. 削除する文字列 (element)
    このメソッドは、指定された要素をセットから削除し、更新されたセットを出力します。

チートシート

remove(element) メソッドは、HashSet から指定された要素が存在する場合にその要素を削除します:

HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.remove("Apple");

自分で試してみよう

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 removeElement(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);
        
        removeElement(set, element);
    }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

ロジックとフローのすべてのレッスン