java.lang.ClassCastException: java.util.HashMap$EntrySet 不能转换为 java.util.Map$Entry

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31832337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:12:30  来源:igfitidea点击:

java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to java.util.Map$Entry

javadictionary

提问by Psl

I have an overrriden method like this

我有一个像这样的重写方法

@Override
public Build auth (Map.Entry<String, String> auth) {
            this.mAuth = auth;
            return this;
}

Here am trying to call this method in the following way

这里我尝试通过以下方式调用此方法

Map<String, String> authentication = new HashMap<String , String> ();        
         authentication.put("username" , "testname");
         authentication.put("password" , "testpassword");        

Map.Entry<String, String> authInfo =(Entry<String , String>) authentication.entrySet();

AuthMethod.auth(authInfo)

While running this am getting

在运行时,我得到

java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to java.util.Map$Entry

How can i pass Map.Entry<String, String>to auth method

我如何传递Map.Entry<String, String>给 auth 方法

采纳答案by Suresh Atta

You are trying to cast a set to a single entry.

您正在尝试将集合转换为单个条目。

You can use each entry item by iterating the set:

您可以通过迭代集合来使用每个条目项:

Iterator it = authentication.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry entry = (Map.Entry)it.next(); //current entry in a loop
    /*
     * do something for each entry
     */
}

回答by Mena

Well, yes.

嗯,是。

You are trying to cast a Set<Map.Entry<String, String>>as a single Map.Entry<String, String>.

您正在尝试将 aSet<Map.Entry<String, String>>作为单个Map.Entry<String, String>.

You need to pick an element in the set, or iterate each entry and process it.

您需要在集合中选择一个元素,或者迭代每个条目并对其进行处理。

Something in the lines of:

在以下方面的东西:

for (Map.Entry<String, String> entry: authentication.entrySet()) {
    // TODO logic with single entry
}

回答by Amila

Map.Entry<String, String> authInfo =(Entry<String, String>) authentication.entrySet();

Here you are doing a wrong cast. The auth method you mentioned seem to be expecting just the values of username/password pair. So something like below would do:

在这里你做错了演员表。您提到的 auth 方法似乎只需要用户名/密码对的值。所以像下面这样的事情会做:

Map<String, String> authentication = new HashMap<String, String>();         
authentication.put("testname", "testpassword");
Map.Entry<String, String> authInfo = authentication.entrySet().iterator().next();
AuthMethod.auth(authInfo)

回答by Ashish Agrawal Yodlee

If we want to return a particular Entry(row), we need to iterate the first entry via iterator.next():

如果我们想返回一个特定的 Entry(row),我们需要通过 iterator.next() 迭代第一个条目:

Map.Entry<String, String> authInfo = (Entry<String, String>)   
authentication.entrySet().iterator().next();

and if we want to iterate over the map, we need to keep this is a loop like:

如果我们想遍历地图,我们需要保持这样的循环:

for( Map.Entry<String, String> authInfo : authentication.entrySet()){
    System.out.println("authInfo:"+authInfo.getKey());
}

回答by Rishabh Mamgain

The below function can be taken as reference for generic iteration, setting, getting values for a map.

下面的函数可以作为通用迭代、设置、获取地图值的参考。

(Iterator<Entry> i = entries.iterator(); i.hasNext(); ) {
    Map.Entry e = (Entry) i.next(); 
    if(((String)e.getValue())==null ){
        i.remove();
    } else {
        e.setValue("false");
    }
    System.out.println(e.getValue());
}

回答by ka4eli

authentication.entrySet()is a collection of Entry. You can process them all like this:

authentication.entrySet()是 的集合Entry。您可以像这样处理它们:

   authentication.entrySet().stream().map(x->auth(x)).collect(Collectors.toList())

回答by cyril

i finally managed to do it but with an ubly way and i really do not understand why it is so complicated

我终于设法做到了,但方法很巧妙,我真的不明白为什么它如此复杂

package utils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

import com.fasterxml.Hymanson.core.JsonParser;
import com.fasterxml.Hymanson.core.JsonProcessingException;
import com.fasterxml.Hymanson.core.type.TypeReference;
import com.fasterxml.Hymanson.databind.DeserializationContext;
import com.fasterxml.Hymanson.databind.JsonDeserializer;
import com.fasterxml.Hymanson.databind.node.ObjectNode;
import com.fasterxml.Hymanson.databind.node.TreeTraversingParser;

import models.Product;
import play.Logger;
import play.libs.Json;

public class ProductDeserializer extends JsonDeserializer<List<Product>>{


@Override
public List<Product> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {

    Map.Entry<String,ObjectNode> map;
    try {   

    TreeTraversingParser parser=(TreeTraversingParser)p;
    Class ftClass = parser.getClass();
    Field nodeCursor = ftClass.getDeclaredField("_nodeCursor");
    boolean nodeCursorAccessible=nodeCursor.isAccessible();
    // Allow modification on the field
    nodeCursor.setAccessible(true);
    Class nodeClass =nodeCursor.get(parser).getClass();
    Field content = nodeClass.getDeclaredField("_current");
    boolean contentAccessible=content.isAccessible();
    content.setAccessible(true);
    map=(Map.Entry<String,ObjectNode>)content.get(nodeCursor.get(parser));
    ObjectNode ob=map.getValue();   
    nodeCursor.setAccessible(nodeCursorAccessible);
    content.setAccessible(contentAccessible);

    return Json.mapper().readValue(ob.get("order_rows").traverse(), new TypeReference<List<Product>>(){});
}catch(Exception e) {
    Logger.error("could not map product for this order"+p.getCurrentValue().toString());
}
    return null;

}

}