问题描述
我将值放入hashmap中,形式为
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);
我想使用 values()创建一个列表地图方法。
List<Double> valuesToMatch=new ArrayList<>(); valuesToMatch=(List<Double>) highLowValueMap.values();
或
List<Double> valuesToMatch=(List<Double>) highLowValueMap.values();
但是,它会引发异常:
线程main中的异常java.lang.ClassCastException:
java.util.HashMap $值不能转换为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
TL;DR
List<V> al = new ArrayList<V>(hashMapVar.values());
说明
c> HashMap#values()返回 java.util.Collection< V> ,并且不能转换集合到 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中转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!