Search code examples
javagenericstype-erasurenested-generics

How can I create an array of items whose entries have generic fields?


I have this code:

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

class Main{
    public static void main (String[] args){
        Foo<String> foo = new Foo<String>(1000);
    }
}

class Foo<Key extends Comparable<Key>>{
    private Entry[] a;
    private class Entry{
        Key key;
    }
    public Foo(int size){
        a = (Entry[])new Object[size]; // <- this is the problem
    }
}

when I compile it, I get an error, saying:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LFoo$Entry;
at Foo.<init>(Main.java:17)
at Main.main(Main.java:7)

I tried:

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

class Main{
    public static void main (String[] args){
        Foo<String> foo = new Foo<String>(1000);
    }
}

class Foo<Key extends Comparable<Key>>{
    private Entry[] a;
    private class Entry{
        Key key;
    }
    public Foo(int size){
        a = new Entry[size];
    }
}

But then I got an error saying:

Main.java:17: error: generic array creation
        a = new Entry[size];
            ^

Is it possible to create that array at all?


Solution

  • Well, actually you can via reflection:

    public class Main {
        public static void main(String[] args) {
            Foo<String> foo = new Foo<String>(1000);
            foo.a[0] = foo.new Entry();
            foo.a[0].key = "ss";
        }
    }
    
    class Foo<Key extends Comparable<Key>> {
        public Entry[] a;
    
        public class Entry {
            Key key;
        }
    
        public Foo(int size) {
            a = (Entry[]) java.lang.reflect.Array.newInstance(Entry.class, size);
        }
    }