解决java.util.HashMap$Values不能被投到java.util.List类的错误

560 阅读1分钟

在这篇文章中,我们将看到如何解决java.util.HashMap$Values不能被投到java.util.List类的错误。

为什么HashMap值不能被投到列表中?

HashMap值返回java.util.Collection ,你不能将Collection投给List或ArrayList。在这种情况下,它将抛出ClassCastException

让我们在例子的帮助下了解一下。

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

输出。

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)

这里是HashMap的value方法的源代码。

public Collection

修复java.util.HashMap$Values不能被投到java.util.List类的问题

我们可以使用ArrayList构造函数来解决这个问题,该构造函数以Collection为参数。

List<Integer> ageList =  new ArrayList<>(nameAgeMap.values());

下面是完整的程序

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

输出。

[23, 20, 28]

这里是ArrayList构造函数的源代码

/**
     * 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

以上就是关于如何解决java.util.HashMap$Values不能被投到java.util.List类的问题。