views:

263

answers:

5

Is it possible to use generics for arrays?

+3  A: 

I don't think this is possible because an array is a basic datatype.

But you can use a ArrayList to have something similar. In most of the cases using a collection of some kind pays of very well.

Janusz
+2  A: 

Have a look at this site. It should contain all generics related FAQs.

On a sidenote:

class IntArrayList extends ArrayList<Integer> { }
IntArrayList[] iarray = new IntArrayList[5];

If you subclass a generic object with a concrete type, that new class can be used as array type.

kd304
+1  A: 

No. Arrays must have a compile-time type.

Ben S
+5  A: 

Arrays are already basic objects types, that is to say they're not a class that describes a collection of other objects like ArrayList or HashMap.

You cannot have an array of generified types either. The following is illegal in Java:

List<String>[] lists = new List<String>[ 10 ];

This is because arrays must be typed properly by the compiler, and since Java's generics are subject to type erasure you cannot satisfy the compiler this way.

banjollity
A: 

It's possible, but far from pretty. In general, you're better of using the Collections framework instead.

See Sun's Generics tutorial, page 15, for a detailed explanation.

jqno