why HashMap Values are not cast in List?

TL;DR

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

Explanation

Because HashMap#values() returns a java.util.Collection<V> and you can’t cast a Collection into an ArrayList, thus you get 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());

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)