Overriding HashSet's Contains Method
collections, hashset, java
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" );
}
Problem
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. :)