The code counts the frequencies of characters of the input string into a char[]
.
Instead of an int[]
.
Which sounds counter-intuitive.
But this leads to an efficient solution, with some limitations.
The trick is that you can create a String
fairly efficiently from a char[]
,
and it will give you the benefits of String.equals
.
A string created from a char[]
that contains character frequencies will not be something readable, but that doesn't matter.
Such string will be usable in a hash table,
as the linked code does,
because String.equals
has an implementation that's suitable to use in hash tables.
By contrast, an int[]
doesn't have a useful implementation of equals
.
This is because arrays inherit the implementation of equals
from Object
,
which is not very useful.
The consequence of this is that a.equals(b)
will return false
when a != b
, even if they both contain the same values.
Thanks to String.equals
,
new String(a).equals(new String(b))
will return true
when a
and b
are char[]
, a != b
, but they contain the same values.
Moreover, there is no way to convert a int[]
to something suitable to use in a hash map that would be faster than new String(char[])
.
The limitation is that if str
contains characters that occur more than 65535 times, then the algorithm will not produce correct output.