• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic for HashMap holding different values

 
Praful Thakare
Ranch Hand
Posts: 642
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
May be too basic question, but haven't worked much on generics,following is my scenario.

I have parentHash map that will hold one more child hashmap for every key, and this childhashmap can hold

1) HashMap <String,HashMap> or
2) HashMap<String,String>.

so how do i define parent hashmap using generics?

-P

 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is not possible for a generic HashMap to hold HashMaps and Strings (unless you're using a Object reference but that will nullify the advantages of generics). A solution would be do separate the 2 Maps in 2 classes and use a common interface to access them.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49796
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Praful Thakare wrote: . . . HashMap <String,HashMap> . . .
Map<String, Map>, surely?
 
Praful Thakare
Ranch Hand
Posts: 642
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks much Wouter, thats cool solution.
 
Praful Thakare
Ranch Hand
Posts: 642
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes Campbell its HashMap<String, HashMap>

-P
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Praful,

Campbell was trying to hint that it should be Map<String, Map>.

John.
 
Praful Thakare
Ranch Hand
Posts: 642
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks John...had doubt abt it but was't sure , but now not able to understand the difference between HashMap<String, HashMap> and Map<Stgring,Map> can you explain ?
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Praful:

It's the idea of programming against interfaces, rather than implementations. For example, if I do this:

I'm locking myself into an implementation - which may at some later point be difficult to change, or may be impossible to change if I expose methods in a public API.

If I do this:

I can be assured that if I need to make a change at a later date (say, like it turns out that a TreeMap would work better), then all I have to do is change that one line of code, and I don't have to worry about my class' public API.

John.
 
Jinglong Wang
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
maybe you can
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic