• Post Reply Bookmark Topic Watch Topic
  • New Topic

Confusion with generics  RSS feed

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is this not allowed
HashMap<String,String>[] baseMap = new HashMap<String, String>[2];
it says cannot create a generic array
 
Marshal
Posts: 56606
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch

It has to do with generics being implemented by erasure.
You would do well to search the Ranch; you find this (by one of our bartenders), and this from the generics FAQ by Angelika Langer which you ought to bookmark.

See whether those links help.
 
Ranch Hand
Posts: 782
Chrome Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays are a deprecated type.

Use:

 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No they're not. If I need a fixed size "collection" I'll always choose an array instead of an ArrayList. An ArrayList uses an array internally (hence the name), and this array is always at least as big as the size of the List. Most times it's bigger though, so most of the time you're wasting array space.

Now that doesn't matter if you know you will use part of that wasted space later on, but if you know you won't an array is just as easy.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!