Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic Array Creation Error Message

 
Kevin Simonson
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
In a map you can store any object so why you need the array of map.
 
Rob Spoor
Sheriff
Pie
Posts: 20531
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic