Java:String:有没有更好的方法来比较字符串

Jas*_*ers 2 java swing

今天早上我感到好奇,如果有人有更好的方法可以徘徊

if(TAG_PLAY.equalsIgnoreCase(e.getActionCommand())
   ||TAG_PASSWORD.equalsIgnoreCase(e.getActionCommand())
   ||...
){
Run Code Online (Sandbox Code Playgroud)

我有一种预感,可以通过创建一个大字符串并在其中查找e.getActionCommand()来改进,但我不知道它是否会更有效

注意:这与getActionCommand无关,我纯粹对逻辑,性能和新方法/模式感兴趣做同样的事情


编辑:我不考虑大写和小写的辩论^^


编辑:

这个怎么样:

s = TAG_PLAY+","+TAG_PASSWORD;
//compareToIgnoreCase is not optimal since it will go through all the String
    if(0!=s.compareToIgnoreCase(anotherString)){
Run Code Online (Sandbox Code Playgroud)

And*_*mas 8

你考虑过使用Set.contains(Object)吗?

例如:

  Set<String> cases = new HashSet<String>();
  cases.add( TAG_PLAY.toLowerCase() );
  cases.add( TAG_PASSWORD.toLowerCase() );

  ...
  if ( cases.contains( e.getActionCommand().toLowerCase() ) { 
  ...
Run Code Online (Sandbox Code Playgroud)


Ano*_*on. 5

如果您正在实现字符串匹配的数据结构,您可能需要某种类型的Trie.

如果您只是想在没有大量代码的情况下在Java中执行此操作,请在集合中查找要匹配的所有字符串,然后检查目标字符串是否在集合中.