Java – an efficient data structure to check whether a string exists
I'm writing a program that will add more and more numbers or unique strings to the data structure Once I'm done, I need to constantly check for strings later
If I use ArrayList, I believe checking for the existence of some specified string will traverse all items until a matching string is found (or reaches the end and returns false)
However, with HashMap, I know that in constant time, I can simply use the key as a string and return any non null object, making this operation faster However, I am not keen on filling in HashMap, its value is completely arbitrary Is there an existing data structure that uses hash functions, but does not need to place values?
Solution
Correct, check that the list of items is linear with the number of items in the list
You don't have to: Java provides a HashSet < T > class, which is very similar to a HashMap without a value part
You can put all strings there and check for other strings for a constant time;
Set<String> kNownStrings = new HashSet<String>(); ... // Fill the set with strings if (kNownString.contains(myString)) { ... }