Overriding HashSet's Contains Method
-
19-09-2019 - |
Question
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. :)
Solution
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" );
}
OTHER TIPS
I would suggest using Google Collections, and in particular, the Sets.filter
method. Much easier than trying to subclass a collection.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow