• Post Reply Bookmark Topic Watch Topic
  • New Topic

Error "incompatible types" when creating a Map  RSS feed

 
Ronald Otto
Greenhorn
Posts: 3
Linux Mac OS X Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a variable



which I initialize like this:



and, using javac 1.7.0_79, get the error message incompatible types. Why? After all, a HashMap is a special kind of a map, and an ArrayList is a special kind of a List.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are correct, but when initializing the map, the formal types of the arguments must match -- you can't use subtypes. The class itself can be a subtype, though.

Translation: You are correct to use HashMap, but it should be List<String>, not ArrayList<String>. That's because the declaration allows for all types of Lists, and you can't alter the declaration.
 
Stevens Miller
Bartender
Posts: 1444
30
C++ Java Netbeans IDE Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think Ronald can finesse the issue entirely by using this to create his map instance:
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
True; I forget about that, because I am stuck in 1.6 land. (And still need to support 1.5).
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!