Skip to content

Hash Map

Sharina Stubbs edited this page Jan 23, 2020 · 5 revisions

Pros

  • Hold key value pairs
  • key value pairs are not in order
  • Let us specify what the data type is for keys and what is data type for values

Cons

  • Can't handle primitives without help, ie, use Integer versus integer.
  • Can only take either one type of data type for keys, and only one type of data type for values, not multiple types of data types for different values.

Object

Does not refer to key value pairs of data, like in JavaScript.

Note on static

If static is before a block of code, such as before a hashmap, it will fill in the values, before any code is written.

Hashmap <String> mapper = new Hashmap<>();
static {
  mapper.put('{');

Example

package demo;

public class Library {
    public boolean someLibraryMethod() {   
        HashMap<String, Integer> shoeSizes = new HashMap<>();
        shoeSizes.put("Jonny", 9);         ^---- note that this is verbally said as 'gets' not 'equals'
        shoeSizes.put("Peter", 12);
        shoeSizes.put("Jackie", 10);
        System.out.println(shoeSizes.get("Nicholas"));
        }
        // To iterate through hash map, iterate through the keys to make life easier. (vice versa is hard)
        for (String name : shoeSizes.keySet())
            System.out.println(name + ": " + shoeSizes.get(name));  //Johny: 9 ,etc
        return true;
    }
}

Sample Code

Code Fellows lecture demo code:

https://github.com/codefellows/seattle-java-401d6/blob/master/class-03/demo/src/main/java/demo/Library.java

Code Fellows lecture demo on searching for items within a text file (Alice in Wonderland)

https://github.com/codefellows/seattle-java-401d6/blob/master/class-03/alice/src/main/java/alice/App.java

Clone this wiki locally