【发布时间】:2021-03-24 21:52:23
【问题描述】:
我需要删除 HashMap 的最后一个输入,然后添加一个新输入。我听说你可以使用 LinkedHashMap 来做到这一点,但具体如何呢?说明没有提到我应该使用 LinkedHashMap,但显然,没有它就不可能从 HashMap 中删除最后一项。
或者,如果您有任何替代解决方案可以删除最后一项以便我可以添加其他输入,请告诉我应该在代码中添加什么。
这是我想要做的:
package studentlist;
import java.util.LinkedHashMap;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class StudentList {
public static void main(String[] args) {
Map<String, String> students = new HashMap<>();
Scanner s = new Scanner(System.in);
for(int i=1; i<= 3; i++){
System.out.print("Enter student number " + i + ": ");
String es = s.nextLine();
System.out.print("Enter student first name " + i + ": ");
String en = s.nextLine();
students.put(es, en);
}
for (Map.Entry mp : students.entrySet()) {
System.out.println(mp.getKey() + " " + mp.getValue());
}
//The 3rd input should be removed before this:
System.out.print("Enter your student number: ");
String sn = s.nextLine();
System.out.print("Enter your first name: ");
String fn = s.nextLine();
students.put(sn, fn);
for (Map.Entry mp : students.entrySet()) {
System.out.println(mp.getKey() + " " + mp.getValue());
}
}
}
【问题讨论】:
标签: java input data-structures hashmap linkedhashmap