So I know normally to create a generic array you could do:
E[] e = (E[]) new Object[10];
However I have a class Entrant<K, V>
which has two generic parameters.
I can't seem to be able to cast an Object array to it.
Here is the full code and error at runtime
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LHashTable.Entrant;
at HashTable.HashTable.<init>(HashTable.java:10)
at Mainy.map(Mainy.java:32)
line 32 in Mainy :
HashTable h = new HashTable();
Hashtable code:
public class HashTable<K, V> {
Entrant<K, V>[] _entrants;
private static final int N = 16;
public HashTable() {
_entrants = (Entrant<K, V>[]) new Object[N]; //line 10
}
}
2 Answers 2
Casting Object[]
to E[]
is not guaranteed to work when you expose the array outside your class. Casting works in constructor because the type of the type parameter E
is erased to Object
, and the cast is effectively equivalent to:
Object[] e = (Object[]) new Object[10];
However, suppose your HashTable
class provides a K[]
array:
class HashTable<K, V> {
K[] _entrants;
private static final int N = 16;
public HashTable() {
_entrants = (K[]) new Object[N]; //line 10
}
public K[] getEntrants() {
return _entrants;
}
}
And you create instance of it, and gets the entrants from it:
HashTable<String, String> hashTable = new HashTable<>();
String[] entrants = hashTable.getEntrants();
That code will throw ClassCastException
in the second assignment.
While in case of parameterized type array, casting would fail as it is erased to:
_entrants = (Entrant[]) new Object[N]; //line 10
Clearly an Object[]
is not a Extrant[]
. So that would fail to work. Rather than doing the cast, you can directly create an array of raw type:
_entrants = new Entrant[N];
and suppress the warning that comes.
Also See:
1 Comment
new Entrant<?, ?>[N]
if you want to avoid raw typesThe logic behind this is :
Every Entrant is an Object, but every object is not an Entrant. See, you are casting Objects to Entrants which won't work.
Object[]
is not anEntrant<K, V>[]
, so you get aClassCastException
. See this question: stackoverflow.com/questions/1817524/generic-arrays-in-java?rq=1