Table of Contents
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package org.arpit.java2blog; import java.util.HashMap; import java.util.List; import java.util.Map; public class HashMapValuesToList { public static void main(String[] args) { Map<String,Integer> nameAgeMap = new HashMap<>(); nameAgeMap.put("John",23); nameAgeMap.put("Martin",20); nameAgeMap.put("Sam",28); List<Integer> ageList = (List<Integer>)nameAgeMap.values(); System.out.println(ageList); } } |
Output:
1 2 3 4 |
Exception in thread "main" java.lang.ClassCastException: class java.util.HashMap$Values cannot be cast to class java.util.List (java.util.HashMap$Values and java.util.List are in module java.base of loader 'bootstrap') at org.arpit.java2blog.HashMapValuesToList.main(HashMapValuesToList.java:15) |
Here is source code of HashMap’s values method.
1 2 3 4 5 6 |
public Collection<V> values() { Collection<V> vs = values; return (vs != null ? vs : (values = new Values())); } |
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.
1 2 3 |
List<Integer> ageList = new ArrayList<>(nameAgeMap.values()); |
Here is complete program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package org.arpit.java2blog; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class HashMapValuesToList { public static void main(String[] args) { Map<String,Integer> nameAgeMap = new HashMap<>(); nameAgeMap.put("John",23); nameAgeMap.put("Martin",20); nameAgeMap.put("Sam",28); // Use ArrayList's constructor List<Integer> ageList = new ArrayList<>(nameAgeMap.values()); System.out.println(ageList); } } |
Output:
Here is source code of ArrayList’s constructor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
/** * Constructs a list containing the elements of the specified * collection, in the order they are returned by the collection's * iterator. * * @param c the collection whose elements are to be placed into this list * @throws NullPointerException if the specified collection is null */ public ArrayList(Collection<? extends E> c) { elementData = c.toArray(); size = elementData.length; // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, size, Object[].class); } |
That’s all about how to fix java.util.HashMap$Values cannot be cast to class java.util.List.