So I know that you cannot \"easily\" create an array of a generic type in Java (but you can create collections). I recently ran across a situation where I needed a 2 dimens
I think the best choice in this situation is to simply use Object[]
.
Prior to generics, array types X[]
where X!=Object
are important types in APIs. We couldn't use List
which couldn't specify the component type. X[]
was the most useful one. Now with generics, we better use List
instead of X[]
in APIs. (JDK still use X[]
in its APIs, even newer APIs, probably because they want to avoid dependencies among their packages)
That's for API. Within implementation details, we still need arrays, they are indispensible. However, Object[]
is enough. Actually if Java keeps only Object[]
and rid all other reference array types, nothing seriously bad would happen. All we need is arrays of objects to write our programs.
Of course, it would be silly to restraint ourselves from using X[]
when it's available and easy to use.
It would be equally silly, when X
is not a simple class, and X[]
is hard to work with, to waste our time to make it work. Nothing good is really achieved. In such situations, just use Object[]
and we'll save ourselves a lot of troubles.
So conclusion: externally, don't accept arrays, and don't give out arrays; internally, use X[]
if there's no sweat, otherewise use Object[]
and be happy.