Search code examples
javaarrayslinkedhashmap

Checking unique values in array using LinkedHashSet in Java


I came across this code on HackerRank, and I really confused myself by understanding this piece of code, which does check uniqueness of the elements in the array using HashMap.

Now to give you an insight, I know how to do this, and it is easy too. But this code is different and I really need to learn how and what it does actually.

int[] seq = new int[]{3,2,1,3};

Integer[] tmp = new Integer[seq.length];
for (int i = 0; i < seq.length; ++i) {
  tmp[i] = Integer.valueOf(seq[i]);
}

/* THIS PIECE OF CODE, HOW THIS WORKS AND WHAT IT DOES???*/         
if (!((new LinkedHashSet<Integer>(Arrays.asList(tmp))).size() == seq.length)) {
    throw new AssertionError("not all values are unique");
}

All I could make out is it converts the arrays into the list of tmp

Arrays.asList(tmp)

2. Converts it to the LinkedHashSet

LinkedHashSet<Integer>(Arrays.asList(tmp))

3. Then finds the size of the HashSet

(LinkedHashSet<Integer>(Arrays.asList(tmp))).size()

4. Compares it to the length of the array seq.

(new LinkedHashSet<Integer>(Arrays.asList(tmp))).size() == seq.length)

And if the length is not equal to the array seq, then how come the elements are unique?


Solution

  • This code creates a LinkedHashSet that contains all the elements of the original array (boxed from int to Integer).

    Since a LinkedHashSet (like all Sets) contains no duplicate elements, the original array has no duplicates if and only if the size of the Set is equal to the length of the array.

    If the array had any duplicates, the size of the Set would have been smaller than the array's length, since the duplicates would have been eliminated when the LinkedHashSet is initialized.