使用泛型Object []的ClassCastException不能转换 [英] ClassCastException using Generics Object[] cannot be cast
问题描述
这是运行它时得到的异常:
[Ljava.lang.Object;无法转换为[Llab09.Entry;
`public class ArrayHeap< K,V>实施PriorityQueue< K,V> {
`私人比较器< K>补偿;
私人条目< K,V> []数据;
private int heapSize;
$ b @SuppressWarnings({unchecked})
public ArrayHeap(int size,Comparator< K> c){
data =(Entry< K,V> [])新对象[size]; //类型转换数组
heapSize = 0;
comp = c;
}
}
另外,我会将嵌套的Entry类放入
受保护的静态类AHEntry 实现Entry< K,V> {
private K k;
private V v;
public AHEntry(K key,V value){
k = key;
v =价值;
}
public K getKey(){return k;}
public V getValue(){return v;}
public void setKey(K key){k = key;}
public void setValue(V value){v = value;}
}
Object
数组不能转换为 Map.Entry
数组。以下代码使用您提供的自定义 AHEntry
类: public class ArrayHeap< K,V>实施PriorityQueue< K,V> {
私人比较器< K>补偿;
私人条目< K,V> []数据;
private int heapSize;
$ b @SuppressWarnings({unchecked})
public ArrayHeap(int size,Comparator< K> c){
data = new(AHEntry< K,V>)new AHEntry<?,?> [size];
heapSize = 0;
comp = c;
}
}
So I'm trying to create a class that implements a heap using an array in order to make a prioritized list. In my constructor I want to create an array of Entry objects. Is this possible to do? I have done some generic casting before and I have tried everything that usually works for me. I feel like It should be possible but i can't figure it out.
This is the exception I get when I run it:
[Ljava.lang.Object; cannot be cast to [Llab09.Entry;
`public class ArrayHeap<K,V> implements PriorityQueue<K,V> {
`private Comparator<K> comp;
private Entry<K,V>[] data;
private int heapSize;
@SuppressWarnings({"unchecked"})
public ArrayHeap(int size, Comparator<K> c){
data = (Entry<K,V>[]) new Object[size]; // type casting array
heapSize = 0;
comp = c;
}
}
Also I'll throw in my nested Entry class to look at aswell.
protected static class AHEntry<K,V> implements Entry<K,V> {
private K k;
private V v;
public AHEntry(K key, V value){
k = key;
v = value;
}
public K getKey(){ return k;}
public V getValue(){ return v;}
public void setKey(K key){ k = key;}
public void setValue(V value){ v = value;}
}
The line data = (Entry<K,V>[]) new Object[size]
is resulting in a type cast error because an Object
array cannot be cast to a Map.Entry
array. The following code makes use of the custom AHEntry
class which you provided:
public class ArrayHeap<K,V> implements PriorityQueue<K,V> {
private Comparator<K> comp;
private Entry<K,V>[] data;
private int heapSize;
@SuppressWarnings({"unchecked"})
public ArrayHeap(int size, Comparator<K> c){
data = new (AHEntry<K, V>)new AHEntry<?, ?>[size];
heapSize = 0;
comp = c;
}
}
这篇关于使用泛型Object []的ClassCastException不能转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!