views:

230

answers:

2

Hello StackOverflow...

Could anybody tell me how I can override HashSet's contains() method to use a regex match instead of just equals()?

Or if not overriding, how I can add a method to use a regex pattern? Basically, I want to be able to run regex on a HashSet containing strings, and I need to match substrings using regex.

If my method is not appropriate, please suggest others.

Thank you. :)

+3  A: 

You could extend a HashSet the following way:

public class RegExHashSet extends HashSet<String > {
    public boolean containsRegEx( String regex ) {
        for( String string : this ) {
            if( string.matches( regex ) ) {
                return true;
            }
        }
        return false;
    }
}

Then you can use it:

RegExHashSet set = new RegExHashSet();
set.add( "hello" );
set.add( "my" );
set.add( "name" );
set.add( "is" );
set.add( "tangens" );

if( set.containsRegEx( "tan.*" ) ) {
    System.out.println( "it works" );
}
tangens
Could you give me a complete code about how to extend HashSet, then initialize a HashSet from the extended class?
Inf.S
I added an example.
tangens
Thanks a lot! :D
Inf.S
This is O(n) with the additional (useless) requirement of hashing on insertion. Assuming the actual .contains() is never used, an ArrayList would work better.
Robert Fraser
An ArrayList would allow multiple instances of the same Object. If you use a Set, you probably want to have only one instance of on Object in it.
tangens
Actually, I need the contains value. However, I need it to match with regex instead of just equals() method.Also, I want only one instance of an object in it. In this case, I want only one instance of each String in it.
Inf.S
+1  A: 

I would suggest using Google Collections, and in particular, the Sets.filter method. Much easier than trying to subclass a collection.

Chris Jester-Young