在https://java-programming.mooc.fi/part-10/2-interface-comparable上做练习“文学”时,我在尝试对 HashMap 中的键值对进行排序时发现了一个非常奇怪的行为,而没有将任何内容复制到一个树形图。我应该通过创建 Book 类并将它们添加到 List 来添加书籍。但是我想在不创建新类的情况下尝试,所以选择了 HashMap。我的代码如下:
public class MainProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<String, Integer> bookshelf = new HashMap<>();
while (true) {
System.out.println("Input the name of the book, empty stops: ");
String bookName = scanner.nextLine();
if (bookName.equals("")) {
break;
}
System.out.println("Input the age recommendation: ");
int age = Integer.valueOf(scanner.nextLine());
bookshelf.put(bookName, age);
}
System.out.println(bookshelf.size() + " book" + (bookshelf.size() > 1 ? "s" : "") + " in total."); …Run Code Online (Sandbox Code Playgroud)