𝗝𝗮𝘃𝗮 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗶𝗼𝗻𝘀: 𝗧𝗵𝗲 𝗛𝗶𝗱𝗱𝗲𝗻 𝗧𝗼𝗼𝗹𝘀 𝗬𝗼𝘂 𝗠𝗶𝘀𝘀
Most developers use Java collections the same way every day. They use ArrayLists and HashSets. But you might be missing tools that make your code faster and safer.
Here are three specific tools to improve your code.
- Arrays.asList is not a true List
When you use Arrays.asList(array), you get a fixed-size list. It links directly to your original array.
- If you change the array, the list changes.
- If you try to add or remove items, your code crashes with an error.
To fix this, wrap it in a new ArrayList:
List
This creates a real, independent list you can modify.
- Use EnumSet for performance
Do you store enums in a HashSet? That creates unnecessary overhead. HashSets use hash tables and object headers.
Use EnumSet instead. It uses a bit vector internally. It is extremely fast and uses almost no memory. It is perfect for flag-based systems like player powers or settings.
- It is type-safe.
- It is much faster than a HashSet.
- It handles bitwise operations for you.
- Use ConcurrentHashMap.computeIfAbsent for caches
If you build a cache, you often write complex code to prevent multiple threads from calculating the same value. This is called double-checked locking. It is hard to read and easy to break.
Instead, use one line: cache.computeIfAbsent(key, this::expensiveCalculation);
This method is atomic. It ensures the calculation runs only once, even if many threads ask for the same key at the same time. It reduces bugs and makes your intent clear.
Why these tools matter:
- Predictable performance: You avoid hidden memory costs.
- Fewer bugs: You stop fighting race conditions in multi-threaded code.
- Clearer code: Other developers understand your design immediately.
Stop fighting the framework. Start using it to write leaner, safer code.