获取Map对象时出现不兼容的类型异常

时间:2016-10-12 16:13:32

标签: java compiler-errors hashmap incompatibletypeerror

我正在研究基于java的应用程序。我有一个地图,我想存储在ehcache中并稍后检索它。下面是代码。

Map<String,String> map = new HashMap<String,String>();
map.put("1","AAA");
map.put("2","BBB");

final Cache cache = getCache(); // creating the cache object
cache.removeAll();
cache.put(new Element("myMap", map));//Storing the java.util.Map object in Cache
//to get the cache
final Element ele = cache.get("myMap");
Map<String,String> map = (ele == null ? null : ele);

它给我发出以下错误

incompatible types. found net.sf.ehcache.Element required java.util.Map<String,String>

请建议我如何将地图对象存储在ehcache中并获取该元素。

2 个答案:

答案 0 :(得分:0)

您的代码注释表明您正在存储地图,但您的代码存储了一个元素。 Element不是地图应该不足为奇。

查看http://www.ehcache.org/apidocs/3.1.3/org/ehcache/Cache.html#put-K-V-的文档,它们非常清楚:

cache.put("myMap", map);

我实际上并不完全确定你的代码是如何编译的。似乎没有带有单个参数的put版本。

答案 1 :(得分:0)

我认为你在嵌套的地图中遇到了混乱(你的地图和EhCache地图)。

所以基本上当你做{cache.put(新元素(&#34; myMap&#34;,map))}}时,你在ehcache map中添加了一个带有id的条目:&#34; myMap&#34;并重视您的地图&#39;。但从技术上讲,此条目是“Element&#39;”类型的单个对象。它封装了ehcache中的键和值。

对于检索回来,您将再次检索一个元素(它已经插入了什么),并从此元素获取值(这是一个映射)。检查如下:

final Cache cache = cacheManager.getCache("123"); // creating the cache object
cache.removeAll();
cache.put(new Element("myMap", map));//Storing the java.util.Map object in Cache
// get your element back
final Element ele = cache.get("myMap");
// get the value of our object. ehcache works with generic objects so you need tocache to your map. Doing a cast since it works with generic object

map = (Map<String, String>) ele.getObjectValue();

我建议您解决这类问题,只需调试代码并检查对象中的数据。然后你可以很容易地弄清楚发生了什么。

相关问题