移除元素
本课属于 Coddy Java 学习旅程的“逻辑与流程”单元。第 24 课,共 59 课。
如果指定的元素存在,remove(element) 方法会将其从 HashSet 中移除。
HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");从集合中移除 "Apple"
fruits.remove("Apple");执行上面的代码后,集合 fruits 中包含:
[]挑战
简单创建一个名为 removeElement 的方法,它接受两个参数:
- 一个由字符串组成的 HashSet(
set) - 一个要移除的 String(
element)
该方法应从集合中移除指定的元素,然后打印更新后的集合。
亲手试试
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);
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: Java 在线编译器