MAPS and HASHMAPS
Objective #1: What is a Map or a HashMap.
- A Map is like an ArrayList where each object can be assigned a string identifier value. A HashMap is a Map in which the values are randomly placed, seeing as i only accessed the values by thier string identifier the order did not matter so i used one of these.
- FROM AUTHOR OF THIS PAGE DYLAN HOGUE (I am guarenteeing that the way i used these to dynamically declare variables) will be highly disencouraged by Mr.Minich, but if you for some reason have around 32 different objects which must have different names and each have four properties which need to be set, I can tell you from experience that using these can take your code from about 6000 lines to maybe between 100 and 1000 lines.)
- A single HashMap can storeany number of one type of an object, even your own
- The greatest use that i got from these was:
- dynamically declare variables/objects
- update the values within each object using one simple for loop
- place all of the components in my program with a double nested forloop for each different type of object
- tell the program what to do if a button was hit (when many buttons) with just a if statement nested inside a for loop
Objective #2: How to declare and impliment a HashMap
- First you must start by adding the following import statements: import java.util.HashMap; AND import java.util.Map;
- Next you must initilize your HashMap object with the following line: Map *name* = new HashMap();
- Your object can be anything, booleans, integers, strings, custom objects, instances of a class, etc.
Objective #3: How to add objects to your HashMap
- First you must have a HashMap declared where the second data type matches the data type of the object you wish to put into it. *Hint from Dylan: If you wish to have a map that accepts most data types then create one that has the second data type as an Object for example- Map allType = new HashMap(); *In this case allType will accept Strings, Integers, Doubles, Booleans, Longs, Chars, any custom class that extends Object, and most other data types(you can do this with Arrays and ArrayLists as well. BUT if you do do this then you will have to cast the item in order to use the correct methods on it (will explain further in objective about retriving data)**
- *My Example will use an integer but either way the same principles apply*
- FROM HERE ON ASSUME THE FOLLOWING HAS BEEN DECLARED: Map numMap = new HashMap();
- In order to add a Integer to your HashMap (numMap) you would use the following code: numMap.put("NumberX", 98);
- You now have '98' stored in your HashMap with the String value "NumberX" as it's reference.
Objective #4: How to retrive data from your HashMap
- Now that we have the value '98' stored in your HashMap you need to know how to retrive it from your HashMap
- As far as retriving our item from a Hash map that only accepts Integers this part is very easy. You just use the code: numMap.get("NumberX"); *Hint from Dylan: Since our references are Strings, it will not tell you if you typed in the wrong string value to get your data. you will just end up with a NullPointerException. So do yourself a favor take the time to double check your strings and make sure that they match up, also stick with simple variable names.*
- Now if you decided to "shortcut" things and use Object as your second data type then you have a tiny bit more to do so everything works right. for example, say i wish to call compareTo("") on a string object i have stored in the HashMap objMap with the reference value "str1"
- To do this i would have to use the line: ((String) objMap.get("str1")).compareTo("");
- In other words you would have to cast the object you are retriving to its accual type
Objective #5: How to change the values of a object stored within a HashMap
- Changing the values stored within a HashMap is very simple once you learn it.
- For this example assume we have already declared a HashMap as intMap and within intMap we have a integer(55) with the string reference value of "int1". Our objective is to change 55 to the value 56.
- For us to do this we would simply "re-add" int1 by using the code: intMap.put("int1", 56);
- When you call the put() method it does not care if you already have a value assigned to the given key or not, it will discard the old value and replace it with the new value. This can cause you trouble in the case of having a HashMap that accepts Object and accidentally replacing one object with another of a different type.
Objective #6: Using HashMaps with Buttons
- For this example assume we already have a HashMap declared named btnMap. Also assume that there are already buttons in this HashMap with the references in the following list {"btn1", "btn2", "btn3", "btn4", "btn5", "btn6", "btn7", "btn8", "btn9", "btn10"} *declaration for one of buttons is immediatly below*
- btnMap.put("btn1", new Button(btn1));
- Adding your ActionListeners and detecting which button was pressed THE LONG WAY
- To add your action listeners this way you would use the code: btnMap.get("btn1").addActionListener(this); for each btn in your HashMap.
- To detect which button is hit this way you have to put the following code inside your actionPerformed(ActionEvent evt) method: if(evt.getSource() == btnMap.get("btn1")){System.out.println("btn1 clicked");} else if(evt.getSource() == btnMap.get("btn2")){System.out.println("btn2 clicked");}.....etc.
- Now as i'm sure you can imagine, this way uses ALOT of code. If that is not something you like then the next way may be better suited for you.
- Adding your ActionListeners and detecting which button was pressed THE SHORT WAY(dynamically and NOT ENCOURAGED unless you have alot of buttons)
- To add your action listeners this way you would use the following code: for(int i = 1; i <= btnMap.size(); i++){btnMap.get("btn" + i).addActionListener(this);}
- as you can see in our example, using this method cuts our code down from 10 lines to just 1 line within a for loop.
- To detect which button is hit this way you have to put the following code inside your actionPerformed(ActionEvent evt) method:for(int i = 1; i <= btnMap.size(); i++){if(evt.getSource() == btnMap.get("btn" + i)){System.out.println("btn" + i + " clicked");}}
- Now doing the button click detection this way of course means that they would have to all call the same method(maybe with a different value for the parameter) or perform basically the same action.(in my application for this it was the first case)
Objective #7: Using HashMaps to declare similar variables dynamically (NOT ENCOURAGED unless you have alot of variables of the same type that will have similar names(I'm putting this here mainly because it is something I needed and I found to be a MAJOR PAIN to find)
- For this example we will be using Strings, assume we have already declared our HashMap as strMap. ALSO assume that we wish to add 25 Strings to our HashMap, all initialized with a null string("")
- *CAUTION: this can be used to initalize each object but to set each value it will need to be done manually, one item at a time(unless you want them all to have the same value)*
- To add all twenty-five Strings to our HashMap at once all we need is a single statement within a For loop as shown below.
- for(int i = 1; i <= 25; i++){strMap.put("str" + i, "");}
- After this runs we now have a HashMap with the following references for each variable {"str1", "str2", "str3", "str4", ......, "str25"}
- As you can see this changed a potential 25 lines into 2 simple lines.
Objective #8: Getting values out of a HashMap that is stored within an ArrayList
- Like many other data types a HashMap can be stored within an ArrayList. In order to retrive a value from a HashMap that is stored within an ArrayList you would access it in basically the same way as if you were accessing a nested arrayList.