Overriding HashSet's Contains Method

吃可爱长大的小学妹 提交于 2019-12-10 18:04:05

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/2015374/overriding-hashsets-contains-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!