Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I create an array of an inner class of a generic type?

The following code gives a "generic array creation" error.

public class TestClass<K, V> {
    Entry[] entry;

    private TestClass() {
        entry = new Entry[10]; // <--- this line gives generic array creation error
    }

    private class Entry {
        public Entry() {

        }
    }
}

I'm wondering why this is, because class Entry is not a generic class and has no objects of generic type.

Is it because the inner class still has access to the generic types, even if it doesn't use any? That's the best I can come up with, though if it were the case, I don't understand why Java couldn't look and see it makes no use of generic types and is therefore not a generic class?

And yes, I have seen many many threads about generic type arrays, but no, I have not found a single one regarding inner classes.

like image 935
bob Avatar asked Jun 30 '15 18:06

bob


1 Answers

The type is actually TestClass<K, V>.Entry (yes it's because it's an inner class). You can solve this by transforming it into a nested static class:

private static class Entry {
    public Entry() {

    }
}
like image 59
M A Avatar answered Nov 15 '22 01:11

M A