Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 550
Psl Avatar asked Aug 05 '15 12:08

Psl


3 Answers

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
     */
}
like image 87
Suresh Atta Avatar answered Nov 09 '22 05:11

Suresh Atta


Well, yes.

You are trying to cast a Set<Map.Entry<String, String>> as a single 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
}
like image 4
Mena Avatar answered Nov 09 '22 05:11

Mena


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:

Map<String, String> authentication = new HashMap<String, String>();         
authentication.put("testname", "testpassword");
Map.Entry<String, String> authInfo = authentication.entrySet().iterator().next();
AuthMethod.auth(authInfo)
like image 3
Amila Avatar answered Nov 09 '22 07:11

Amila