File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Generic Array Creation Error Message Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generic Array Creation Error Message" Watch "Generic Array Creation Error Message" New topic
Author

Generic Array Creation Error Message

Kevin Simonson
Ranch Hand

Joined: Oct 22, 2011
Posts: 103
I've got a piece of code I'm including here that attempts to create an array of "Map< Side, String>" objects:

When I try to compile it I get the message:

C:\Users\kvnsmnsn\Java\Wade>javac Ma.java
Ma.java:12: generic array creation
= new EnumMap< Side, String>[ arguments.length >> 1];
^
1 error

C:\Users\kvnsmnsn\Java\Wade>

Why is it illegal to create an array of "EnumMap< Side, String>"s?

Kevin Simonson
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Kevin:

Because generics in Java don't work that way. You can't assign an array of EnumMap<T, U> to an array of Map<T, U>.

John.
abani patra
Ranch Hand

Joined: Oct 11, 2011
Posts: 70
Hi,
In a map you can store any object so why you need the array of map.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19653
    
  18

John de Michele wrote:Kevin:

Because generics in Java don't work that way. You can't assign an array of EnumMap<T, U> to an array of Map<T, U>.

Actually you can, once you are able to create one. Because Map is a super type of EnumMap, Map[] is a super type of EnumMap[].
Creating the array is the problem, because generics don't allow you to create arrays of generic types. The reason is because the compiler cannot guarantee type safety anymore. Consider, assuming line 1 would not create a compiler error:
With non-generic types line 3 would have already created a ClassCastException, and therefore it's easier to find the cause of the problem. In this case the ClassCastException comes at a point where you no longer know why it went wrong.

Anyway, with only one compiler warning you can create the values map:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generic Array Creation Error Message
 
Similar Threads
Wierd Socket Behavior
passing arguments from command-line to Point(x,y)
What exactly Does <setExecutable()> Do on a Windows Machine?
Quick String to <char> Array Conversion
Simple J2SE 5.0 Tiger Notes