providence
providence

Reputation: 29463

Not sure how to avoid this ClassCastException

The following code throws a ClassCastException. The collection in question actually does hold ArrayList<String>.

HashMap listing = (HashMap) data.get(s);
Collection<ArrayList<String>> collection = listing.entrySet();

int count = 0;


for ( ArrayList al : collection ) // exception occurs here
{
    count += al.size();
}

I am assuming that this must be converted to Object and

a) I can't seem to figure out how to convert from Object to ArrayList properly

b) I'm not even sure if thats the issue..

Perhaps someone can provide some insight?

Edit: HashMap listing is a HashMap<String, ArrayList<String>>

Upvotes: 1

Views: 749

Answers (3)

Kanagaraj M
Kanagaraj M

Reputation: 679

Your code has problem in second line listing.entrySet() always return Set<MapEntry<Key,Value>> That cannot be casted to Collection<ArrayList<String>> even though set is a subtype of collection because the generics are differ.

And then in the HashMap(listing) what is the type of key and value?

Upvotes: 1

Suraj Chandran
Suraj Chandran

Reputation: 24801

I think the most pluasible place where the exception is occuring is at the following line : HashMap listing = (HashMap) data.get(s);

Are you sure data.get(s) is suppose to return hashmap.

Also entrySet returns a set that is incompatible incompatible to your assignment.

Upvotes: 0

Jim Garrison
Jim Garrison

Reputation: 86774

HashMap.entrySet() returns Set<Map.Entry<K,V>>. This is not compatible with Collection<ArrayList<String>>.

As a side note, your HashMap is a raw type and should be parameterized.

Upvotes: 1

Related Questions