为什么 HashMap 值不在 List 中转换? [英] why HashMap Values are not cast in List?

查看:25
本文介绍了为什么 HashMap 值不在 List 中转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将值放入形式为的哈希图中,

I'm putting values into the hashmap which is of the form,

Map<Long, Double> highLowValueMap=new HashMap<Long, Double>();
highLowValueMap.put(1l, 10.0);
highLowValueMap.put(2l, 20.0);

我想使用 map 的 values() 方法创建一个列表.

I want to create a list by using values() method of map.

List<Double> valuesToMatch=new ArrayList<>();
valuesToMatch=(List<Double>) highLowValueMap.values();

List<Double> valuesToMatch=(List<Double>) highLowValueMap.values();

但是,它会引发异常:

线程主"java.lang.ClassCastException 中的异常:
java.util.HashMap$Values 不能转换为 java.util.List

Exception in thread "main" java.lang.ClassCastException:
java.util.HashMap$Values cannot be cast to java.util.List

但它允许我将其传递给创建列表:

But it allows me to pass it in to the creation of a list:

List<Double> valuesToMatch  = new ArrayList<Double>( highLowValueMap.values());

推荐答案

TL;DR

List<V> al = new ArrayList<V>(hashMapVar.values());

说明

因为 HashMap#values() 返回一个 java.util.Collection 并且您不能将 Collection 转换为ArrayList,因此你得到 ClassCastException.

Explanation

Because HashMap#values() returns a java.util.Collection<V> and you can't cast a Collection into an ArrayList, thus you get ClassCastException.

我建议使用 ArrayList(Collection<? extends V>) 构造函数.这个构造函数接受一个实现 Collection<? 的对象.扩展 V> 作为参数.当您像这样传递 HashMap.values() 的结果时,您不会得到 ClassCastException:

I'd suggest using ArrayList(Collection<? extends V>) constructor. This constructor accepts an object which implements Collection<? extends V> as an argument. You won't get ClassCastException when you pass the result of HashMap.values() like this:

List<V> al = new ArrayList<V>(hashMapVar.values());

深入了解 Java API 源代码

HashMap#values():检查源代码中的返回类型,并问自己,java.util.Collection是否可以强制转换为java.util.ArrayList?没有

Going further into the Java API source code

HashMap#values(): Check the return type in the source, and ask yourself, can a java.util.Collection be casted into java.util.ArrayList? No

public Collection<V> values() {
    Collection<V> vs = values;
    return (vs != null ? vs : (values = new Values()));
}

ArrayList(Collection):检查源中的参数类型.参数是超类型的方法可以接受子类型吗?是的

ArrayList(Collection): Check the argument type in the source. Can a method which argument is a super type accepts sub type? Yes

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);
}

这篇关于为什么 HashMap 值不在 List 中转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆