[Fixed] java.util.HashMap$Values cannot be cast to class java.util.List

[ad_1]

 

HashMap values cannot be cast to list

In this post, we will see how to fix error java.util.HashMap$Values cannot be cast to class java.util.List.

Why HashMap values cannot be cast to list?

HashMap values returns java.util.Collection and you can not cast Collection to List or ArrayList. It will throw ClassCastException in this scenario.

Let’s understand with the help of example:

Output:

Here is source code of HashMap’s values method.

Fix for java.util.HashMap$Values cannot be cast to class java.util.List

We can use ArrayList‘s constructor which takes Collection as parameter to resolve this issue.


Here is complete program

Output:

[23, 20, 28]

Here is source code of ArrayList’s constructor

That’s all about how to fix java.util.HashMap$Values cannot be cast to class java.util.List.

[ad_2]

Important Interview Questions answer

More Course

Free Courses Enroll Today

Leave a Comment