map和hashmap如何删除条目

v1uwarro  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(376)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

26天前关门了。
改进这个问题
我很难用java来做这个map和hashmap,因为我还在学习它。所以我们有这个活动,我已经完成了一半,我的问题是我不知道如何删除java中条目的Map。有人知道怎么做吗。谢谢。

import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;

public class StudentList {

public static void main(String[] args) {
Scanner input = new Scanner (System.in);
Map<String,String> Student = new HashMap<>();

for (int i=1;i<=3;i++){
    System.out.print("Enter student number " + i + ": ");
    String num = input.nextLine();
    System.out.print("Enter first name " + i + ": ");
    String name = input.nextLine();
    Student.put(num,name);
}
System.out.println("Student List:");
for(Map.Entry List:Student.entrySet())
    System.out.println(List.getKey()+ "  " +List.getValue());
}
}
//This is the output of it.   
Enter student number 1: 0004
Enter first name 1: Mary
Enter student number 2: 0018
Enter first name 2: Nica
Enter student number 3: 0145
Enter first name 3: Mae
Student List:
0018  Nica   // I also have a problem here, idk why Nica is 1st on the list and not Mary.
0004  Mary
0145  Marc

//This is the part of the instruction in our activity.
The output shall:
-Ask three (3) of your classmates to enter their student number (key) and first name (value).
-Display the keys and values of the map.
-Delete the mapping of the third entry
-Enter your student number and first name. This would be the new third entry.        
-Display the entries in separate lines.
ibps3vxo

ibps3vxo1#

Map#删除

从数据库中删除条目(键值对) Map ,呼叫 Map#remove 在传递钥匙的时候。
对你来说,你的钥匙是 Integer 对象(文件的装箱版本) int 基本值)。所以如果你想删除 3 :

String nameValueOfEntryRemoved = map.remove( 3 ) ;

您可能需要检查返回值是否正确 null 不管怎样。

迭代顺序

你还问:
为什么妮卡排在第一位而不是玛丽
你为什么指望玛丽第一个?这个 HashMap 你以前的班级没有这样的承诺。引用javadoc的第一段:
……此类不保证Map的顺序;特别是,它不能保证随着时间的推移,订单将保持不变。
如果你想把钥匙放得井井有条,就用一把钥匙 SortedMap 实施或 NavigableMap 实施。
如果希望密钥保持原始插入顺序,请使用以下实现: LinkedHashMap .
这是我做的一张图表,帮助你选择一个合适的选择 Map 实施。

相关问题