What is the fastest way to know if a letter exists in a Character collection
- Should I define a hashmap with something like "A" , new Character("A")
- should I use something like a sorte开发者_如何转开发d list ? or cast it into an int?
- 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;
精彩评论