覆盖HashSet的包含方法 [英] Overriding HashSet's Contains Method
本文介绍了覆盖HashSet的包含方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人能告诉我如何重写HashSet的contains()方法来使用正则表达式匹配而不是equals()?
Could anybody tell me how I can override HashSet's contains() method to use a regex match instead of just equals()?
或者如果不覆盖,可以添加一个方法来使用regex模式?基本上,我想要能够在包含字符串的HashSet上运行regex,我需要使用regex匹配子字符串。
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.
谢谢。 :)
推荐答案
您可以通过以下方式扩展HashSet:
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;
}
}
那么你可以使用它:
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" );
}
这篇关于覆盖HashSet的包含方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文