After using the ArrayList mentioned in my last post, I thought to see what the HashMap is all about. Once defined, the HashMap takes a "key" and a "value". In the code snippet below, the "1" is the key and the "JAN" is the value.
These are used within database code where within a table, there will be a key in one column and a value in the other column. Not being into extreme database programming that would require the use of a key/value, thought it would be useful to at least understand how to code these.
ArrayFunction1() was coded to put the key/value into myHashMap.
ArrayFunction2() was coded to extract various items from myHashMap.
If this looks familiar, it is a direct copy of the ArrayList() in the previous post as well. Found it very convenient were all that was needed was a search/replace operation.
public static HashMap <Integer, String> ArrayFunction1 () {
HashMap<Integer, String> myHashMap = new HashMap<Integer, String>();
Logger("ArrayFunction1: Entry");
...
myHashMap.put(1,"JAN");
myHashMap.put(2,"FEB");
myHashMap.put(3,"MAR");
myHashMap.put(4,"APR");
...
Logger("ArrayFunction1: Exit");
}
public static void ArrayFunction2 (HashMap<Integer, String> myinputarray) {
Logger("ArrayFunction2: Entry");
...
Logger("ArrayFunction2: keySet: " + myinputarray.keySet());
Logger("ArrayFunction2: entrySet: " + myinputarray.entrySet());
Logger("ArrayFunction2: values: " + myinputarray.values());
...
Logger("ArrayFunction2: Exit");
}
And this is the output. It shows the keySet(), and entrySet() and the values() that are in the HashMap. I left out some of the boolean methods (containsValue()), containsKey()). They work pretty cool, showing true or false if the item is present in either the key or value.
ArrayFunction2: keySet: [1, 2, 3, 4]
ArrayFunction2: entrySet: [1=JAN, 2=FEB, 3=MAR, 4=APR]
ArrayFunction2: values: [JAN, FEB, MAR, APR]
Wondering what that Logger() function is? It is that method shown in the previous post that accepts a String as the only argument and simply outputs the input string to stdout. In otherwords, Logger() is a just wrapper to System.out.println().
No comments:
Post a Comment