𝗠𝗮𝘀𝘁𝗲𝗿 𝗝𝗮𝘃𝗮 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗶𝗼𝗻𝘀
Most developers default to ArrayList or HashSet. This works for simple tasks. It fails when you need speed or scale.
I once built a game leaderboard using a plain ArrayList. I sorted it every time a score changed. The UI froze constantly. I was fighting the language instead of using it.
Stop using the wrong tools. Use these three specialized collections to write faster, cleaner code.
- EnumSet for Enum Constants
If you use HashSet for enums, you pay a performance tax. Every insertion boxes the enum into an object. This adds unnecessary overhead.
EnumSet uses a bit vector. It performs checks using a single CPU instruction.
- Use it when you have a fixed set of enum values.
- It reduces garbage collection.
- It provides 10x speed increases in tight loops.
Before:
Set
After:
EnumSet
- NavigableSet for Range Queries
Manually looping through a sorted list to find a range is slow and prone to errors. You often end up with off-by-one bugs.
NavigableSet keeps your data sorted automatically. It provides O(log n) lookups for subsets.
- Use it for high-score tables or price ranges.
- Use headSet() or subSet() to grab specific ranges.
- It removes the need for manual sorting code.
Before:
Collections.sort(scores);
List
After:
NavigableSet
- CopyOnWriteArrayList for Read-Heavy Lists
Using synchronized blocks on an ArrayList slows down every read. It also causes ConcurrentModificationException if one thread writes while another reads.
CopyOnWriteArrayList creates a new copy of the array on every write. Readers look at a snapshot of the array.
- Use it for event listeners or configuration settings.
- Use it when reads happen much more often than writes.
- It allows lock-free reads.
Before:
List
After:
CopyOnWriteArrayList
Stop defaulting to the same two collections. Pick the tool that matches your data pattern.
Source: https://dev.to/timevolt/the-java-collections-force-mastering-the-hidden-gems-like-a-jedi-4438