我的地图会在一段时间内填写。问题是我想知道最后添加的条目是什么。到目前为止,我只找到了地图中的最后一个条目。有没有办法获得最后添加的条目?
到目前为止代码:
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}
已经陈述的顺序是我以后必须使用的顺序。
答案 0 :(得分:3)
http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html
也就是说,这可能无法满足您的特定需求,我会阅读文档。
它很简单,可以扩展现有的实现,以提供更多控制。
答案 1 :(得分:0)
您可以创建自己的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;}
}
或者那种影响。