映射与缺失的键
Coddy 面向 C 开发者的 Java 课程的第 14 课,共 48 课。
标准 C 不提供通用的字符串键映射;必须由表或库定义查找和插入行为。Java 的 Map.get 不会插入不存在的键,并且可能返回 null,因此拆箱并不安全。请使用 containsKey 或合适的备用值,并选择 TreeMap 来按键的自然顺序排序,而不要假设 HashMap 会保留插入顺序。
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdarg.h>
#include <errno.h>
#include <limits.h>
#include <ctype.h>
int main(void) {
struct Entry {const char *name;int total;}; struct Entry entries[]={{"free",0}}; int total=-1; bool found=false; for(size_t i=0;i<1;i++) if(strcmp(entries[i].name,"free")==0) {total=entries[i].total;found=true;} printf("%d %s\n",total,found?"true":"false");
return 0;
}
Java
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Example {
public static void main(String[] args) {
Map<String,Integer>counts=new HashMap<>();counts.put("red",counts.getOrDefault("red",0)+1);System.out.println(counts.get("red"));
}
}
这些示例分别展示各语言的行为,也可能使用不同的值。请分别跟踪每个示例的执行过程,不要假设它们的预期输出相同。Java 任务会通过可编辑的类,将同一概念应用于新的输入。
挑战
简单输入是一行由空白字符分隔的小写单词。统计每个单词出现的次数,并按字母顺序排列,以多行 word:count 条目的形式返回。输入为空时,返回 empty。
返回 Exercise.solve(List<String> input) 的确切结果文本,末尾不带换行符。可见的锁定文件 Main.java 会读取所有输入行,并在打印返回的文本时添加一个末尾换行符。不要在可编辑的方法中打印内容。除非另有说明,所有整数和算术结果都符合 Java int 的范围。
可编辑文件:Exercise.java、Text.java。Text.java 提供可重复使用的解析和格式化辅助方法。所有文件都位于未命名包中,并会一起编译。Main.java 是唯一的入口点,不能编辑。
亲手试试
import java.io.*;
import java.util.*;
public class Main {
private static void check(boolean condition) {
if (!condition) throw new AssertionError("Required public API behavior failed");
}
public static void main(String[] args) throws Exception {
List<String> input = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = reader.readLine()) != null) input.add(line);
System.out.println(Exercise.solve(input));
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 Java中的所有课
自己练习: Java 在线编译器