Ecology lab



HashMapJava Collections are much more than just better arrays, however. Here we introduce the hash map. A hash map is a one-to-one relationship between one object and another. Let me explain it another way for those who don't want to remember math. Let's say you want to access your email account. You can't do this right away though, so you're taken to a login screen. At this login screen you type in your username and password, and then when the combination is correct you can access your email account.A hashmap works similarly. You have to give it an appropriate input so you can get the proper output. Each input is mapped to exactly one output. In our previous example, one combination of username and password produces exactly one email account. Here's a code example: Again, you will be missing an import statement. In general you can get the import you need by typing: import java.util.NameOfObject where NameOfObject is the Collection you're using, in this case HashMap. You can also just hit Ctrl+Shift+O to automatically import everything in Eclipse.If we look at HashMap we just created, you will see . This means that the first value (the key) is a String, and the second value is also a String. You can have any combination of objects, of course.You use the key to obtain its value. One key corresponds to exactly one value, just like one username corresponds to one password.Inserting new key/value pairs is simple: And this is how you delete them: If you want an array of all the keys in the hash map, you can use the keySet() method: This is fairly tricky. The keySet method returns a Set. Then, that set is turned into an array of Strings by creating a new String that has a length that's the size of the HashMap. Then, that array is stored in an array called keys. The reason I'm creating an array of Strings is because the keys are all Strings from before. How are hash maps useful? They let you store objects by looking up other objects instead of index values like you would with an ArrayList. Using the example above, if you needed to look up the password to someone's account, you could search the HashMap for the password by using the username as the key. Note: I repeat, you CANNOT store basic (primitive) types inside of ArrayLists, HashMaps, or ANY Java collection for that matter. Java collections only store objects. This is EXTREMELY IMPORTANT so do not forget.Read more: ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download