HashMap

The HashMap class allows you to store information (a value) that can be retrieved using its "key". Each key in a HashMap is unique.

An example of when a HashMap could be used is in a school. There may be more than one student with the same name, but each student is given a unique ID number that allows you to find the correct student. In this case, the HashMap "keys" are ID numbers, and the "values" are Student records (objects). See below:

Student s1 = new Student("Sarah", 123);
Student s2 = new Student("Sarah", 555);
Student s3 = new Student("Joe", 345);

HashMap<Integer, Student> students = new HashMap();
students.put(s1.ID, s1);
students.put(s2.ID, s2);
students.put(s3.ID,s3);

String student = students.get(555); //student will be Sarah with ID 555

Things to find out before you finish this module:

  • How to create and inititialize a HashMap

  • How to put/get keys and values into/out of a HashMap

  • How to loop through all the elements of a HashMap (advantages and disadvantages of different types of loop)

  • Advantages and disadvantages of HashMaps
  • Sample Program

    HashMapDemo

    Student Recipes

    IntroToHashMaps
    LogSearch