//直接继承的才可以转型的观点是错误的,不好意思,误导了. 比如:
Collection<Integer> c = new ArrayList<>();
ArrayList<Integer> list = (ArrayList<Integer>) c;
// 继承关系:
// java.util.AbstractCollection<E>
// java.util.AbstractList<E>
// java.util.ArrayList<E
// 这个装换是没有问题的
Animal animal = new Dog();
Animal animal1 = new Cat();
Cat cat = (Cat)animal;
// Exception in thread "main" java.lang.ClassCastException: test.Dog cannot be cast to test.Cat
// 同样的例子 :
Collection<Integer> values = new HashMap<Integer,Integer>().values();
ArrayList<Integer> list1 =(ArrayList<Integer>) values;
// 输出:Exception in thread "main" java.lang.ClassCastException: java.base/java.util.HashMap$Values cannot be cast to java.base/java.util.ArrayList
//
// 大概意思就是 HashMap的内部类Values(狗)不能装换成 HashMap(猫)
源码:
public Collection<V> values() { Collection<V> vs = values; if (vs == null) { vs = new Values(); values = vs; } return vs; } final class Values extends AbstractCollection<V> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); } public final Iterator<V> iterator() { return new ValueIterator(); } public final boolean contains(Object o) { return containsValue(o); } public final Spliterator<V> spliterator() { return new ValueSpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer<? super V> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (Node<K,V> e : tab) { for (; e != null; e = e.next) action.accept(e.value); } if (modCount != mc) throw new ConcurrentModificationException(); } } }
//////////////////////////////////////////////////////////////////////////////解决你的问题//mljqqh/////////////网/你 ///////////////////////////