Menu
CoddyTech

回顾:HashMap

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

challenge icon

挑战

简单

创建一个名为 processHashMap 的方法,它接收一个 HashMap<String, Integer> 和一个由 String 操作组成的数组,然后执行以下操作:

1. GET 操作

  • 格式:"GET key"
  • 操作:
    • 如果键存在:打印它的值
    • 如果键不存在:打印 "Not found"

2. CHECK 操作

  • 格式:"CHECK key"
  • 操作:
    • 如果键存在:打印 "Exists"
    • 如果键不存在:打印 "Not found"

3. MODIFY 操作

  • 格式:"MODIFY key targetValue"
  • 操作:
    • 如果键存在,并且它的当前值等于 targetValue:使用 replace() 将值更新为 targetValue + 1
    • 如果键存在,但它的当前值与 targetValue 不同:使用 remove() 删除该键
    • 如果键不存在:使用 put() 添加该键,并将 targetValue 设为它的值
  • 注意:执行 MODIFY 操作时不要打印任何内容

最终输出:

处理完所有操作后,该方法应返回修改后的 HashMap。main 方法会以 JSON 格式打印它。

亲手试试

// 将 hashmap 字符串转换为 hashmap 所需的模块
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
// -----------------------------
import java.util.HashMap;
import java.util.Scanner;

public class Main {
    public static HashMap<String, Integer> processHashMap(HashMap<String, Integer> data, String[] operations) {
        // 在这里编写你的代码
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String hashMapString = scanner.nextLine();
        String operationsString = scanner.nextLine();

        // 将 HashMap 的 String 转换为 HashMap
        Type mapType = new TypeToken<HashMap<String, Integer>>(){}.getType();
        HashMap<String, Integer> data = new Gson().fromJson(hashMapString, mapType);

        // 将 Array 的 String 转换为 Array
        String[] operations = new Gson().fromJson(operationsString, String[].class);

        HashMap<String, Integer> result = processHashMap(data, operations);
        System.out.println(new Gson().toJson(result));
    }
}

逻辑与流程中的所有课

自己练习: Java 在线编译器