Tuesday, June 7, 2016

Building a Study Guide App with Java Hashmap

These days, a physical dictionary is pretty old-fashioned. The idea of consulting a physical book to learn the meaning of a word or phrase makes no sense when a simple Google search will give you all the information you need.

But a dictionary provides a very useful metaphor for an important programming concept: key-value pairs. Dictionaries operate by linking a word (a "key") to its meaning (a "value"). The key-value pair is a fundamental data model in programming.

Most programming languages use hashes to ensure the uniqueness of keys and make storage and retrieval of values more efficient. A HashMap in Java puts all of that together to allow programmers to store key-value pairs by hashing their keys upon insertion and retrieval.

In this tutorial, we'll learn how to build a study guide program by storing Java concepts and their corresponding meanings in a HashMap to be retrieved when it’s time to study.

[author_more]

HashMap

Java maps make programs more efficient by storing key-value pairs in a single data structure. Alternatively, the same could be accomplished with two manually synced data structures -- one holding keys and the other holding values -- but this isn't the best approach to mapping keys to values; that's what a Map is for. The HashMap is arguably one of the most powerful of them all. All keys of the map must be of the same type, as must its values.

~~In the background, Java's HashMap class stores the pairs in arrays, but we don't have to worry much about the implementation because much of the heavy lifting is encapsulated and I think it's safe to trust that the Java developers know what they are doing.~~

The Map interface provides methods for putting pairs in the map, replacing the value of pairs, removing pairs by key, checking for the existence of a pair by key, and clearing the map. We'll make use of almost all of those functions today.

The Application

Our app will be a simple study guide app. We'll build our HashMap to store our concepts and use Java control-flow statements to loop until we have provided the correct meaning for each concept. Let's build!

Classes

We'll need two classes to run our study guide application. The first class will be our main class to run our program and the second will be another class to model the meaning of Java concepts and encapsulate a couple of fields and methods to simplify the study guide interface.

The first thing we need to do is create a new Java project with a main class. Once we have that set up, let's go ahead and build our Meaning class that will be used in our Main.

Continue reading %Building a Study Guide App with Java Hashmap%


by Lincoln Daniel via SitePoint

No comments:

Post a Comment