简体   繁体   中英

What is the fastest way to know if a letter exists in a Character collection

  1. Should I define a hashmap with something like "A" , new Character("A")
  2. should I use something like a sorted list ? or cast it into an int?
  3. simple list? (that doesnt seem too efficient )

I need a fast retrieving - when I ask if the Char exists. adding time is almost none important.

As we're talking about a Collection : It depends on the collection type . A HashSet offers the best performance for contains operations, which is O(1).

Set<Character> chars = new HashSet<Character>();
chars.add(new Character('A'));    
chars.add(new Character('B'));
chars.add(new Character('C'));

if (chars.contains('A'))
  System.out.println("Lightning fast answer: TRUE");

A char is an unsigned 16-bit value and can take on only 65,536 values. Since you talk about existence, I am kind of assuming you have a Set and not a general Collection . Use a BitSet to represent this set; add and check the existence of a char as if it is an integer value (because it is). This is the fastest I can imagine, will be faster for sure than a regular HashSet of Character`, and it takes just 8K of memory.

If you don't process the whole range of unicode characters, a simple (bit/bool) array should be reasonably fast. Compared to a hash you won't have to worry about collisions, too.

What is the size of your alphabet? If it is small and all characters are ASCII characters you can use array.

boolean[] chars;
chars['A'] = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM