繁体   English   中英

检查HashMap是否被修改(添加或修改的值)

[英]Check if HashMap was modified (values added or modified)

我有一个遍历HashMap的方法,以获取所有值的总整数。 如果自上次调用此方法以来未更改HashMap,我想避免遍历整个地图并查找总和。

如何检查HashMap中是否修改了新值或旧值? 有这种方法吗?

扩展HashMap; 覆盖更改值的方法,并设置一个标志,指示某些值已更改。 提供一种方法来测试该值,并可能提供一种方法来对其进行重置。 如果这是应用程序中的问题,请考虑并发性。

(我相信您了解如何扩展一个类,并且重写方法并不意味着您必须重新实现所有这些方法(super是您的朋友)。乍一看,整个类对我来说似乎都不是,超过30-40行代码。)

我添加了一个新的答案,该答案不会受到时钟变通办法的影响:

public class YourMap<K, V> extends HashMap<K, V> {

    private int state = 0;

    public YourMap() {
        super();
    }

    @Override
    public V put(K key, V value) {
        state++;
        return super.put(key, value);
    }

    public boolean isUpdated(int state) {
        return (state < this.state);
    }

    public int getState() {
        return state;
    }
    ... // Do the same with clear, remove... methods.
}

然后在您的代码中:

public static void Main() {
    new YourMap<Integer, Integer> myMap = new YourMap<Integer, Integer>();
    int state = myMap.getState();
    myMap.put(1, 2);
    System.out.println(myMap.isUpdated(state));  // will print true.
    if (!myMap.isUpdated()) {  // in this demo, it will never go in this if.
        // call your process...
    }
}

这是有效的,并且currentTimeMilliseconds不会有问题。

public class HashMapWithLastModified<K,V> extends HashMap<K,V> {
    private long lastModified;

    @Override
    public V put(K key, V value) {
        lastModified = System.currentTimeMillis();
        return super.put(key, value);
    } 

    @Override
    public V remove(Object key) {
        lastModified = System.currentTimeMillis();
        return super.remove(key);
    }

    @Override
    public void clear() {
        lastModified = System.currentTimeMillis();
        super.clear();
    }

    public boolean modifiedSince(Date toCheck) {
        return lastModified >= toCheck.getTime();
    }
}

暂无
暂无

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

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