TIL: Java Maps, Synchronization, and Other Fun Stuff
Today’s going to be a bit of a mixed pot of things as I read through different areas of Java and take notes on what I learn.
Using Hash Tables
So off to the internet I went looking for some sort of answer as to how this is commonly handled in the Java world.
My search first took me to
HashTables are an older implementation (like the 90’s). They offer something called
synchronization (more on that later) out of the box, and were better suited for multi threaded applications at the time. However, everyone pretty much calls them legacy at this point and highly recommends against them as the synchronization can also be achieved on
HashMaps as well.
There’s quite a bit of discussion on the topic of
HashTable over on Stack overflow, all much more thought out than I have any capacity or athority to try and convey.
My takeaways from this are the following though:
- Use a HashMap regardless. No reason not to.
- The normal HashMap is unordered.
- HashMap supports 1 null key and unlimited null values.
- If you need a predictable way of iterating over the Map, use a
- If thread safety is an issue (more than one thread), start looking into using
Here’s how I ended up implementing the Map in my solution:
This seems to be the word that Java uses to refer to thread safety when accessing resources (or it’s a more common term that’s new to me). Much of what I read on the subject was specific to the Hash talk above.
There seemed to be a loud part of the population that warned against taking a synchronized method as being some magical thing that would prevent any collisions from happening. The general consensus seemed to be that who ever was writing the code needs to be sure to take their time to ensure that logic is added to check on resources ON TOP OF using synchronization.
Regex is incredibly painful
Glad I spent all of that time working through regex… As if it weren’t already confusing enough, Java seems to make it incredibly hard for you to even use it on string matches. Yay.
Iterating Over Strings
There’s a much easier way to iterate over strings than what I’d been trying to do before.
length method will give you the current length of the string, but you won’t be able to just index it like you would in python. However, there’s another method,
charAt, that WILL let you use the index to retrieve the value. This will give you the char at that position and you can do whatever you need to do with it.
Also somewhat related, you can just go ahead and add characters onto strings that you already have, just by contacting them onto the end!