If I have an unor开发者_StackOverflow社区dered character array, how can I get the unique elements?
One-liner:
Set<Character> uniqueChars = new HashSet<Character>(Arrays.asList(array));
(the array
will need to be Character[]
not char[]
. Otherwise you'd have to convert it to the wrapper array)
Note that, if this is homework, you would need a more algorithmic approach in order to show that you understand what you are doing. The above solution may not be applicable. But here's how it works:
- the array is turned into a
List
. This isO(1)
, as the array just backs the new, unmodifiable list. This is done so that the array can conform the theList
interface, which is required by theHashSet
constructor - a
HashSet
is a collection backed by aHashMap
(hashtable). It computes the hashes of keys and stores them in an internal array, under an index = hash. Thus lookup is O(1). - the
HashSet
constructor simply iterates the passedList
and callsadd(..)
for each item. Items that are the same are not allowed twice in the set (sets by definition do not allow duplicates). This is so, because the hash of the item will be the same as an existing one, so the new one will replace the old one. Note that items with the same hash are allowed, but not those that are also equal (.equals(..)
)
精彩评论