开发者

How can I get the unique elements of an unordered character array in Java?

开发者 https://www.devze.com 2023-03-09 02:07 出处:网络
If I have an unor开发者_StackOverflow社区dered character array, how can I get the unique elements?One-liner:

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 is O(1), as the array just backs the new, unmodifiable list. This is done so that the array can conform the the List interface, which is required by the HashSet constructor
  • a HashSet is a collection backed by a HashMap (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 passed List and calls add(..) 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(..))
0

精彩评论

暂无评论...
验证码 换一张
取 消