Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 242
  • Last Modified:

Need a container to hold a unique list of strings with a fast lookup

Hi,

I need to maintain a list of unique strings. What container should I use? I need the following requirements:

1) check to see if the string exists in the container (note that it could be a different String object with the same text)
2) must be fast. I mean I don't want the container to be looping through each element doing an equals() call for each element

So I'm thinking it should be some kind of container where the Strings are added in sorted order. This way any kind of equals call can use a divide and conquer approach to testing or something similar.

Are there any containers like this? Whether inside the JDK or freely available somewhere?

Or does anyone have any suggestions the best way to build one?
0
ycomp
Asked:
ycomp
  • 3
  • 2
1 Solution
 
lhankinsCommented:
You can do this with one of the java.util.Set implementations (either HashSet or TreeSet).

Both implementations are fast with respect to lookup time.   If you want to maintain the items in sorted order (e.g. you want to print them out in sorted order), then use the TreeSet.   Otherwise, use the HashSet.

Example usage :

      Set items = new HashSet();

      items.add("foo");
      items.add("bar");
      items.add("wubba");
      // etc...
     
      if (items.contains("somestring"))
      {
         // item is in the set...
      }


0
 
lhankinsCommented:
BTW - all of the classes listed above are part of the standard JDK (they are in the java.util package).
0
 
ycompAuthor Commented:
ah, so HashSet does use equals() or something to test? I tried it in my code but it didn't work. I guess I was calling it wrong.
0
 
ycompAuthor Commented:
I forgot about hashcodes. It's been a long day.
0
 
ycompAuthor Commented:
yeah was my faulty code that caused the problem
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now