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. :)
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" );
}
I would suggest using Google Collections , and in particular, the Sets.filter
method. Much easier than trying to subclass a collection.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.