简体   繁体   English

如何删除 hasmap 中的前 2 个密钥对

[英]how to remove the first 2 key-pairs in hasmap

I asks the user to put 2 key pairs我要求用户输入 2 个密钥对

for (int j = 0; j < 2; j++) {
        System.out.print("Enter student ID " + (j + 1) + ": ");
        id = sc.next();
        System.out.print("Enter student name " + (j + 1) + ": ");
        name = sc.next();
        studentList.put(id, name);
    }

then I removed the last pair the user entered然后我删除了用户输入的最后一对

studentList.remove(id);

I ask for another pair and added it into the hashmap我要了另一双并将其添加到 hashmap

System.out.println("Enter username: ");
    username = sc.next();
    System.out.println("Enter password: ");
    password = sc.next();
    studentList.put(username, password);

now, I want to ask the user again for another 3 pair现在,我想再次向用户询问另外 3 对

for (int y = 0; y < 3; y++) {
        System.out.print("Enter username " + (y + 1) + ": ");
        username = sc.next();
        System.out.print("Enter password " + (y + 1) + ": ");
        password = sc.next();
        studentList.put(username, password);
    }

but now, I want to remove the first 2 the user put.但是现在,我想删除用户放置的前 2 个。

You can use interfaces SortedMap or NavigableMap for deleting first two key-pairs, but you can NOT do it with HashMap, because it doesn't save order.您可以使用接口 SortedMap 或 NavigableMap 删除前两个密钥对,但不能使用 HashMap 执行此操作,因为它不保存顺序。 As a hashmap has no order it makes no sense to delete the first entry.由于 hashmap 没有顺序,因此删除第一个条目没有任何意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM