Search code examples
javagenericstype-erasure

How to store a generic array of objects the type of which implements some inteface?


I have run into the following issue. I have an array of objects of some generic type, I know that due to type erasure you have to do:

X[] a = (X[])new Object[size];

But unfortunately it doesn't work when X implements some interface. Here are the two examples describing what I mean:

1 (works) :

import java.util.*;
import java.lang.*;
import java.io.*;

class Foo<X>{
    private X[] a = (X[])new Object[2]; 
}

class Main {
    public static void main (String[] args) throws java.lang.Exception {
        Foo<Integer> foo = new Foo<Integer>();
    }
}

2(doesn't work):

import java.util.*;
import java.lang.*;
import java.io.*;

class Foo<X extends Comparable<X>>{
    private X[] a = (X[])new Object[2]; //doesn't work
}

class Main {
    public static void main (String[] args) throws java.lang.Exception {
        Foo<Integer> foo = new Foo<Integer>();
    }
}

Do I have to resort to storing everything as an Object and cast all the type in this case? And why does this happen?

The error message that I get for the second example is :

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object;    cannot be cast to [Ljava.lang.Comparable;
at Foo.<init>(Main.java:10)
at Ideone.main(Main.java:17)

Solution

  • Thanks to immibis, changing

    (X[])new Object[size];
    

    to

    (X[])new Comparable[size];
    

    worked.