Tutorials Point puts it best
"Like Hashtable stores key/value pairs in a hash table. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table."
A hashtable can be a solution if you have two pieces of data that are linked. Perhaps you need a zip code for a street, or you want to keep a count on multiple peoples balances.
A brief example
Alright lets break this down.
Hashtable <String,Double> myTable = new Hashtable();
myTable.put("John Doe", 350.99);
myTable.put("Ralph Wiggum", 55.88);
myTable.put("Jim Jimson", 30.99);
System.out.println(myTable.get("John Doe"));
First we have the declaration. We have declared that this hash table accepts strings and Doubles, not primitive doubles, but the wrapper class.Hashtable <String,Double> myTable = new Hashtable();
Using the .put() method, we can fill up the hash table with various names and numbers. This is all very well and good, but what can we do with it? Well, if you only have somebodies name, and want to know how much money they owe you, assuming that is what we are storing.
myTable.put("John Doe", 350.99);
myTable.put("Ralph Wiggum", 55.88);
myTable.put("Jim Jimson", 30.99);
System.out.println(myTable.get("John Doe"));
This results in the following output:
Hurray! We now know that John owes us 350.99 of something. Hash tables can even be linked to each other. So you could have a hash table that stores names, numbers and addresses by linking to three different hash tables. Perhaps I will return to this in future posts, showing it more in depth.
If you want to know more about hashtables. Please consult some of these links:
http://www.tutorialspoint.com/java/java_hashtable_class.htm
https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html
Thank you.
No comments:
Post a Comment