• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

generics and arrays

 
Jim Lang
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear ranchers,

This is a bit of a painful one, since I know that Java 5 does not permit the construction of generic arrays. It seems strange that this is not permitted since to implement collection classes using arrays would be a natural thing to do.

Fair enough, I see it's not a proper type to create an array with, and I can see that generics are only doing their thing at compile-time (so this might cause problems for runtime type-checking) but shouldn't there be some sort of way to do this using 'nice' java?

Can anyone suggest a way to do this that isn't a nasty hack (or an only mildly nasty hack if there's no nice way to do it)?

Many thanks - Jim
 
Jeff Mayer
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe something like that:

?
 
Ricky Clarkson
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The simplest way is to not use arrays. Arrays are not fully typechecked at compile time:

Number[] numbers=new Integer[1];
numbers[0]=5.0; //ArrayStoreException

That's the main reason why they're incompatible with generics.

If you're absolutely convinced that using arrays is what you want, use the factory pattern.

interface ArrayFactory<T>
{
T[] instance();
}

public <T> void doSomething(ArrayFactory<T> factory)
{
System.out.println(factory.instance());
}

Obviously this isn't a useful example.

In my opinion, Java 5 wasn't fit for release while there were generics warnings from classes such as ArrayList.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15441
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"This is a bit of a painful one, since I know that Java 5 does not permit the construction of generic arrays. It seems strange that this is not permitted since to implement collection classes using arrays would be a natural thing to do."

It is strange indeed, I've written a blog post once to explain exactly why it works like this in Java: Java generics quirks.

Basically the reason why this doesn't work is because the Java compiler uses type erasure, so that the array store check does not have all the information available at runtime that it needs. I think Sun implemented generics using type erasure only because they didn't want to radically change the class file format in Java 5. Unfortunately we're now stuck with it - it seems unlikely that in future versions of Java we will get rid of type erasure.
 
Ricky Clarkson
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Reification is being considered for Java 7.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic