重写 HashSet 的 Contain 方法

发布于 2024-08-17 00:11:31 字数 203 浏览 2 评论 0原文

有人能告诉我如何重写 HashSet 的 contains() 方法以使用正则表达式匹配而不是仅使用 equals() 吗?

或者,如果不覆盖,我如何添加一个方法来使用正则表达式模式?基本上,我希望能够在包含字符串的 HashSet 上运行正则表达式,并且我需要使用正则表达式来匹配子字符串。

如果我的方法不合适,请推荐其他方法。

谢谢。 :)

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. :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情话已封尘 2024-08-24 00:11:31

您可以通过以下方式扩展 HashSet:

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" );
}

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" );
}
对你再特殊 2024-08-24 00:11:31

我建议使用 Google 收藏集,特别是 Sets.filter 方法。比尝试对集合进行子类化要容易得多。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文