重构此Java代码,检查String是否包含任何这些可能性?

Jas*_*ldo 3 java string refactoring loops

我需要检查一个字符串是否不包含任何这些字符串的可能性:

MNC BRA LEB MAR RVC WAY GLZ WWW HYB

我目前的代码:

 if(selectedLocation.equals("OTH"))
 {
    if(!currentClassLocation.equals("MNC") &&
                        !currentClassLocation.equals("BRA") &&
                        !currentClassLocation.equals("LEB") &&
                        !currentClassLocation.equals("MAR") &&
                        !currentClassLocation.equals("RVC") &&
                        !currentClassLocation.equals("WAY") &&
                        !currentClassLocation.equals("GLZ") &&
                        !currentClassLocation.equals("WWW") &&
                        !currentClassLocation.equals("HYB"))
                    {
                         //Awesome, I need this string! I operate on it here.
                    }
 }
Run Code Online (Sandbox Code Playgroud)

长话短说,我不能使用for-loop.有没有办法我可以检查字符串是否包含任何这些没有迭代?

Bri*_*ham 9

使用HashSet:

Set<String> invalidSequences = new HashSet<String>();
invalidSequences.add("MNC");
invalidSequences.add("BRA");
invalidSequences.add("LEB");
// Remaining sequences ...

if (!invalidSequences.contains(currentClassLocation)) {
    // Awesome, I need this string...
}
Run Code Online (Sandbox Code Playgroud)

  • 代码到界面; 即`Set <String> invalidSequences = new HashSet <String>();` (5认同)