9. Does Hash Map Key Value need to be same data type for each?


#1

The code for creating a Hash Map is something like...

HashMap<String, Integer> myFriends = new HashMap<String, Integer>();

This leads me to believe that the data types for every single HashMap object must be of the same data types? In the above code the object can only ever have a string and an integer?

But what if we wanted for example to create a HashMap for a person with several data types? One being an int, another being a string, another being a boolean etc.

Is this possible?

In JavaScript you would do something like...

var person = {
  name: "John Doe",
  age: 22,
  student: true,
  grades: [95, 80, 75, 100]
}

In the javascript code above we have an object with key/value pairs that are different for each. We have a string, an integer, a boolean, and even an array.

Can we do anything like this is Java?

https://www.codecademy.com/en/courses/learn-java/lessons/data-structures/exercises/hashmap?action=lesson_resume&link_content_target=interstitial_lesson


#2

@jaydacoder,
I would read some
== discussions / opinions ==
http://stackoverflow.com/questions/14599317/hashmap-holding-different-data-types-as-values
and
http://stackoverflow.com/questions/40471/differences-between-hashmap-and-hashtable?rq=1
found with google search
java can a hashmap have several datatype site:stackoverflow.com


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.