Menu
CoddyTech

检查元素是否存在

本课属于 Coddy Java 学习旅程的“逻辑与流程”单元。第 25 课,共 59 课。

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
challenge icon

挑战

简单

创建一个名为 checkElement 的方法,它接受两个参数:

  1. 一个字符串的 HashSet(set)
  2. 一个要检查的字符串(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);
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: Java 在线编译器