𝗠𝗮𝘀𝘁𝗲𝗿 𝗝𝗮𝘃𝗮 𝗖𝗼𝗹𝗹𝗲𝗰𝘁𝗶𝗼𝗻𝘀

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.

  1. 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.

Before: Set abilities = new HashSet<>(); abilities.add(Ability.FIRE);

After: EnumSet abilities = EnumSet.of(Ability.FIRE);

  1. 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.

Before: Collections.sort(scores); List topTen = scores.subList(size - 10, size);

After: NavigableSet scores = new TreeSet<>(Comparator.reverseOrder()); scores.add(1542); NavigableSet topTen = scores.headSet(scores.first(), true).stream().limit(10).collect(Collectors.toCollection(TreeSet::new));

  1. 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.

Before: List log = Collections.synchronizedList(new ArrayList<>()); // Iterating here can crash if a writer joins in.

After: CopyOnWriteArrayList log = new CopyOnWriteArrayList<>(); // Iteration is safe and never crashes.

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