在 LinkedHashMap 上使用 put 方法时出现 NullpointerException
我使用 LinkedHashMap 作为缓存。我已经重写了removeEldestEntry,以强制此缓存具有固定大小。旧值将被删除。这就是我的地图的初始化方式:
<!-- language: lang-java -->
sBackgroundBitmapCache = new LinkedHashMap<String, Bitmap>(backgroundCacheSize) {
private static final long serialVersionUID = 287204858147490218L;
@Override
protected boolean removeEldestEntry(LinkedHashMap.Entry<String, Bitmap> eldest) {
if (size() > backgroundCacheSize) {
Log.d(TAG, "Removing hash " + eldest.getKey() + " from background cache");
return true;
} else {
return false;
}
}
};
所以显然我将使用 put 方法来使用该缓存。但在使用 put 方法时,我收到崩溃报告:
java.lang.NullPointerException
at java.util.LinkedHashMap.postRemove(LinkedHashMap.java:291)
at java.util.HashMap.remove(HashMap.java:637)
at java.util.LinkedHashMap.addNewEntry(LinkedHashMap.java:186)
at java.util.HashMap.put(HashMap.java:411)
我一直无法找到为什么使用 put 方法可能会导致空指针异常。我 100% 确定,键和值不为空。
任何帮助将不胜感激。
-f4
I'm using a LinkedHashMap as cache. I've overridden removeEldestEntry in order to force this cache to have a fixed size. Older values will be removed. This is how my map is initialized:
<!-- language: lang-java -->
sBackgroundBitmapCache = new LinkedHashMap<String, Bitmap>(backgroundCacheSize) {
private static final long serialVersionUID = 287204858147490218L;
@Override
protected boolean removeEldestEntry(LinkedHashMap.Entry<String, Bitmap> eldest) {
if (size() > backgroundCacheSize) {
Log.d(TAG, "Removing hash " + eldest.getKey() + " from background cache");
return true;
} else {
return false;
}
}
};
So obviously I'm going to use that cache using put method. But I'm getting crash reports, when using put method:
java.lang.NullPointerException
at java.util.LinkedHashMap.postRemove(LinkedHashMap.java:291)
at java.util.HashMap.remove(HashMap.java:637)
at java.util.LinkedHashMap.addNewEntry(LinkedHashMap.java:186)
at java.util.HashMap.put(HashMap.java:411)
I haven't been able to find why, using put method, may cause a nullpointer exception. I'm 100% sure, key and value are not nulls.
Any help will be appreciated.
-f4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如迈克所说,问题可能与尝试从多个线程使用缓存有关。我遇到了同样的问题,并且似乎已经通过确保所有 put() 都发生在 UI 线程中来修复它。
As Mike said, the problem could be related to trying to use the cache from multiple threads. I had the same problem and seem to have fixed it by making sure all the put()s happened from the UI thread.