If I have an unordered character array, how can I get the unique elements?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
One-liner:
(the
arraywill need to beCharacter[]notchar[]. 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:
List. This isO(1), as the array just backs the new, unmodifiable list. This is done so that the array can conform the theListinterface, which is required by theHashSetconstructorHashSetis 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).HashSetconstructor simply iterates the passedListand 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(..))