And since LinkedHashMap derives from HashMap, you can use it in the same places as you would a regular HashMap (i.e. I’ve been running around the java.util package for a while now, but until this requirement came up, I’d never even given LinkedHashMap a second look. Sometimes it pays to look around the API a little bit and see what all is out there. Once I started using LinkedHashMap, everything started working perfectly. It keeps track of the keys based on insertion order, so that when you do a call to getKeySet(), you will get the keys back in the order you put them in. The data structure I was looking for is the LinkedHashMap. When I tried it out I found out that because I was using Strings as the key, it alphabetized them, which is not what I was looking for. TreeMap will keep the keys sorted, so I thought all was well. My first thought when I need something in an ordered collection in Java is to run to the TreeMap (or TreeSet depending on the data situation). not in the insert order, and not in alphabetical order either). I’d never run into this particular scenario before, so I didn’t really give it much thought until I kept noticing that my keys were coming out in a crazy order (i.e. The other day I ran into a situation where I needed to pull the keys from the HashMap in the same order that I put them in. Python doesn’t have this problem because everything is an Object.) It seems like I’m always using HashMaps to organize my data. Which is a bummer because while you can create an Integer out of an int, it leads to more code which looks less streamlined. (In Java, the key and the value have to Objects, so using primitives like int are out. They aren’t as good/useful as Python’s dictionaries, but they are still really useful. HashMaps are pretty cool, they allow you to access you information using a “named” index. 14 October 2006 An ordered HashMap in Java
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |