1

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
    }

}
Rohit Jain
  • 195,192
  • 43
  • 369
  • 489
  • 2
    What you are trying to do does not work. An `Object[]` is not an `Entrant[]`, so you get a `ClassCastException`. See this question: http://stackoverflow.com/questions/1817524/generic-arrays-in-java?rq=1 – Jesper Mar 31 '14 at 11:21
  • also.. Please follow standard Java naming conventions - camelCase for instance – TheLostMind Mar 31 '14 at 11:22

2 Answers2

4

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:

Community
  • 1
  • 1
Rohit Jain
  • 195,192
  • 43
  • 369
  • 489
0

The 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.

TheLostMind
  • 34,842
  • 11
  • 64
  • 97