• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Generic Array Creation Error Message

 
Ranch Hand
Posts: 248
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
In a map you can store any object so why you need the array of map.
 
Sheriff
Posts: 22787
131
Eclipse IDE Spring Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic