Collection with no duplicates and in random order in Java

duplicates, java, list, set, shuffle

Solution

You can maintain two separate collections, an `ArrayList` and a `HashSet`, and reject insertion of any item which is present in the `HashSet`.

If you are concerned with encapsulation, wrap the two collections in a meta-object that implements `List`, and carefully document that insertions of duplicate elements will be rejected, even if the general contract of `List` doesn't prescribe so.

Talking about the cost of this solution, I believe that in terms of time the cost would be absolutely negligible if compared to a plain `ArrayList`: most operations on `HashSet`s cost amortized O(1), namely lookup and insertion. On the other hand, your memory usage will be twice (or more, depending on the `HashSet` load factor).

Problem

It looks like I can't either use an ArrayList nor a Set: `Set<>` - I can avoid duplicates using a set, but no shuffle option // `Collections.shuffle(List<?> list)` `ArrayList<>` - I can use shuffle to randomise the list, but duplicates are allowed. I could use a `Set` and convert this into an `ArrayList` (or the other way around) to avoid the duplicates. Alternatively, loop through the set to randomise the items. But I am looking for something more efficient.

Original source

Related problems