有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java获取映射中最后添加的条目

我有一张地图,很快就会被填满。问题是我想知道最后添加的条目是什么。到目前为止,我只找到了地图上的最后一个条目。有办法得到最后添加的条目吗

迄今为止的代码:

        int spawned = 0;
     NavigableMap<String, Integer> minioncounter = new TreeMap<String, Integer>();

    while (spawned < 7) {
        if(!minioncounter.containsKey("big")){
            minioncounter.put("big", 1);
        }else if(!minioncounter.containsKey("small")){
            minioncounter.put("small", 1);
        }else if(minioncounter.containsKey("small") && minioncounter.get("small")  < 2){
            minioncounter.put("small", 2);
        }else if(!minioncounter.containsKey("archer")){
            minioncounter.put("archer", 1);
        }else{
            minioncounter.put("archer", minioncounter.get("archer")+1);
        }
        spawned++;  
        System.out.println(minioncounter.);
        System.out.println(minioncounter);

}

当前控制台输出:

{big=1}
{big=1, small=1}
{big=1, small=2}
{archer=1, big=1, small=2}
{archer=2, big=1, small=2}
{archer=3, big=1, small=2}
{archer=4, big=1, small=2}

已经说明的顺序是我以后必须使用的顺序


共 (2) 个答案

  1. # 1 楼答案

    ^{}

    这个Map实现按照键的插入顺序(基本上)维护键。也就是说,这可能无法满足您的特定需求,我已经阅读了文档

    不过,扩展现有实现以提供更多控制非常简单

  2. # 2 楼答案

    您可以创建自己的StoreLastAddMap类来包装真正的NavigableMap。在类中公开put方法,在调用包装的NavigableMap的add方法之前,将更新对最后添加项的引用

    public class StoreLastAddMap () {
    
        NavigableMap<String, Integer> minioncounter = new TreeMap<String, Integer>();
        private String lastAddedKey;
    
        put(String key, Integer val) {
            lastAddedKey = key;
            minioncounter.put(key, val);
        }
    
        //getter for the wrapped Map to do other Map related stuff
        NavigableMap getMap() {return minioncounter;}
    
        Integer getLastAddedVal(){return minioncounter.get(lastAddedKey);}
    
        String getLastAddedKey() {return lastAddedKey;}
    }
    

    或者类似的东西